1// Copyright 2021 Google LLC
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     https://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15// Code generated by protoc-gen-go_gapic. DO NOT EDIT.
16
17package retail
18
19import (
20	"context"
21	"fmt"
22	"math"
23	"net/url"
24	"time"
25
26	"cloud.google.com/go/longrunning"
27	lroauto "cloud.google.com/go/longrunning/autogen"
28	gax "github.com/googleapis/gax-go/v2"
29	"google.golang.org/api/option"
30	"google.golang.org/api/option/internaloption"
31	gtransport "google.golang.org/api/transport/grpc"
32	retailpb "google.golang.org/genproto/googleapis/cloud/retail/v2"
33	longrunningpb "google.golang.org/genproto/googleapis/longrunning"
34	"google.golang.org/grpc"
35	"google.golang.org/grpc/codes"
36	"google.golang.org/grpc/metadata"
37)
38
39var newProductClientHook clientHook
40
41// ProductCallOptions contains the retry settings for each method of ProductClient.
42type ProductCallOptions struct {
43	CreateProduct  []gax.CallOption
44	GetProduct     []gax.CallOption
45	UpdateProduct  []gax.CallOption
46	DeleteProduct  []gax.CallOption
47	ImportProducts []gax.CallOption
48}
49
50func defaultProductClientOptions() []option.ClientOption {
51	return []option.ClientOption{
52		internaloption.WithDefaultEndpoint("retail.googleapis.com:443"),
53		internaloption.WithDefaultMTLSEndpoint("retail.mtls.googleapis.com:443"),
54		internaloption.WithDefaultAudience("https://retail.googleapis.com/"),
55		internaloption.WithDefaultScopes(DefaultAuthScopes()...),
56		option.WithGRPCDialOption(grpc.WithDisableServiceConfig()),
57		option.WithGRPCDialOption(grpc.WithDefaultCallOptions(
58			grpc.MaxCallRecvMsgSize(math.MaxInt32))),
59	}
60}
61
62func defaultProductCallOptions() *ProductCallOptions {
63	return &ProductCallOptions{
64		CreateProduct: []gax.CallOption{
65			gax.WithRetry(func() gax.Retryer {
66				return gax.OnCodes([]codes.Code{
67					codes.Unavailable,
68					codes.DeadlineExceeded,
69				}, gax.Backoff{
70					Initial:    100 * time.Millisecond,
71					Max:        60000 * time.Millisecond,
72					Multiplier: 1.30,
73				})
74			}),
75		},
76		GetProduct: []gax.CallOption{
77			gax.WithRetry(func() gax.Retryer {
78				return gax.OnCodes([]codes.Code{
79					codes.Unavailable,
80					codes.DeadlineExceeded,
81				}, gax.Backoff{
82					Initial:    100 * time.Millisecond,
83					Max:        60000 * time.Millisecond,
84					Multiplier: 1.30,
85				})
86			}),
87		},
88		UpdateProduct: []gax.CallOption{
89			gax.WithRetry(func() gax.Retryer {
90				return gax.OnCodes([]codes.Code{
91					codes.Unavailable,
92					codes.DeadlineExceeded,
93				}, gax.Backoff{
94					Initial:    100 * time.Millisecond,
95					Max:        60000 * time.Millisecond,
96					Multiplier: 1.30,
97				})
98			}),
99		},
100		DeleteProduct: []gax.CallOption{
101			gax.WithRetry(func() gax.Retryer {
102				return gax.OnCodes([]codes.Code{
103					codes.Unavailable,
104					codes.DeadlineExceeded,
105				}, gax.Backoff{
106					Initial:    100 * time.Millisecond,
107					Max:        60000 * time.Millisecond,
108					Multiplier: 1.30,
109				})
110			}),
111		},
112		ImportProducts: []gax.CallOption{
113			gax.WithRetry(func() gax.Retryer {
114				return gax.OnCodes([]codes.Code{
115					codes.Unavailable,
116					codes.DeadlineExceeded,
117				}, gax.Backoff{
118					Initial:    100 * time.Millisecond,
119					Max:        60000 * time.Millisecond,
120					Multiplier: 1.30,
121				})
122			}),
123		},
124	}
125}
126
127// ProductClient is a client for interacting with Retail API.
128//
129// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls.
130type ProductClient struct {
131	// Connection pool of gRPC connections to the service.
132	connPool gtransport.ConnPool
133
134	// flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE
135	disableDeadlines bool
136
137	// The gRPC API client.
138	productClient retailpb.ProductServiceClient
139
140	// LROClient is used internally to handle longrunning operations.
141	// It is exposed so that its CallOptions can be modified if required.
142	// Users should not Close this client.
143	LROClient *lroauto.OperationsClient
144
145	// The call options for this service.
146	CallOptions *ProductCallOptions
147
148	// The x-goog-* metadata to be sent with each request.
149	xGoogMetadata metadata.MD
150}
151
152// NewProductClient creates a new product service client.
153//
154// Service for ingesting Product information
155// of the customer’s website.
156func NewProductClient(ctx context.Context, opts ...option.ClientOption) (*ProductClient, error) {
157	clientOpts := defaultProductClientOptions()
158
159	if newProductClientHook != nil {
160		hookOpts, err := newProductClientHook(ctx, clientHookParams{})
161		if err != nil {
162			return nil, err
163		}
164		clientOpts = append(clientOpts, hookOpts...)
165	}
166
167	disableDeadlines, err := checkDisableDeadlines()
168	if err != nil {
169		return nil, err
170	}
171
172	connPool, err := gtransport.DialPool(ctx, append(clientOpts, opts...)...)
173	if err != nil {
174		return nil, err
175	}
176	c := &ProductClient{
177		connPool:         connPool,
178		disableDeadlines: disableDeadlines,
179		CallOptions:      defaultProductCallOptions(),
180
181		productClient: retailpb.NewProductServiceClient(connPool),
182	}
183	c.setGoogleClientInfo()
184
185	c.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool))
186	if err != nil {
187		// This error "should not happen", since we are just reusing old connection pool
188		// and never actually need to dial.
189		// If this does happen, we could leak connp. However, we cannot close conn:
190		// If the user invoked the constructor with option.WithGRPCConn,
191		// we would close a connection that's still in use.
192		// TODO: investigate error conditions.
193		return nil, err
194	}
195	return c, nil
196}
197
198// Connection returns a connection to the API service.
199//
200// Deprecated.
201func (c *ProductClient) Connection() *grpc.ClientConn {
202	return c.connPool.Conn()
203}
204
205// Close closes the connection to the API service. The user should invoke this when
206// the client is no longer required.
207func (c *ProductClient) Close() error {
208	return c.connPool.Close()
209}
210
211// setGoogleClientInfo sets the name and version of the application in
212// the `x-goog-api-client` header passed on each request. Intended for
213// use by Google-written clients.
214func (c *ProductClient) setGoogleClientInfo(keyval ...string) {
215	kv := append([]string{"gl-go", versionGo()}, keyval...)
216	kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version)
217	c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...))
218}
219
220// CreateProduct creates a Product.
221func (c *ProductClient) CreateProduct(ctx context.Context, req *retailpb.CreateProductRequest, opts ...gax.CallOption) (*retailpb.Product, error) {
222	if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines {
223		cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond)
224		defer cancel()
225		ctx = cctx
226	}
227	md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent())))
228	ctx = insertMetadata(ctx, c.xGoogMetadata, md)
229	opts = append(c.CallOptions.CreateProduct[0:len(c.CallOptions.CreateProduct):len(c.CallOptions.CreateProduct)], opts...)
230	var resp *retailpb.Product
231	err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
232		var err error
233		resp, err = c.productClient.CreateProduct(ctx, req, settings.GRPC...)
234		return err
235	}, opts...)
236	if err != nil {
237		return nil, err
238	}
239	return resp, nil
240}
241
242// GetProduct gets a Product.
243func (c *ProductClient) GetProduct(ctx context.Context, req *retailpb.GetProductRequest, opts ...gax.CallOption) (*retailpb.Product, error) {
244	if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines {
245		cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond)
246		defer cancel()
247		ctx = cctx
248	}
249	md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName())))
250	ctx = insertMetadata(ctx, c.xGoogMetadata, md)
251	opts = append(c.CallOptions.GetProduct[0:len(c.CallOptions.GetProduct):len(c.CallOptions.GetProduct)], opts...)
252	var resp *retailpb.Product
253	err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
254		var err error
255		resp, err = c.productClient.GetProduct(ctx, req, settings.GRPC...)
256		return err
257	}, opts...)
258	if err != nil {
259		return nil, err
260	}
261	return resp, nil
262}
263
264// UpdateProduct updates a Product.
265func (c *ProductClient) UpdateProduct(ctx context.Context, req *retailpb.UpdateProductRequest, opts ...gax.CallOption) (*retailpb.Product, error) {
266	if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines {
267		cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond)
268		defer cancel()
269		ctx = cctx
270	}
271	md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "product.name", url.QueryEscape(req.GetProduct().GetName())))
272	ctx = insertMetadata(ctx, c.xGoogMetadata, md)
273	opts = append(c.CallOptions.UpdateProduct[0:len(c.CallOptions.UpdateProduct):len(c.CallOptions.UpdateProduct)], opts...)
274	var resp *retailpb.Product
275	err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
276		var err error
277		resp, err = c.productClient.UpdateProduct(ctx, req, settings.GRPC...)
278		return err
279	}, opts...)
280	if err != nil {
281		return nil, err
282	}
283	return resp, nil
284}
285
286// DeleteProduct deletes a Product.
287func (c *ProductClient) DeleteProduct(ctx context.Context, req *retailpb.DeleteProductRequest, opts ...gax.CallOption) error {
288	if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines {
289		cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond)
290		defer cancel()
291		ctx = cctx
292	}
293	md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName())))
294	ctx = insertMetadata(ctx, c.xGoogMetadata, md)
295	opts = append(c.CallOptions.DeleteProduct[0:len(c.CallOptions.DeleteProduct):len(c.CallOptions.DeleteProduct)], opts...)
296	err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
297		var err error
298		_, err = c.productClient.DeleteProduct(ctx, req, settings.GRPC...)
299		return err
300	}, opts...)
301	return err
302}
303
304// ImportProducts bulk import of multiple Products.
305//
306// Request processing may be synchronous. No partial updating is supported.
307// Non-existing items are created.
308//
309// Note that it is possible for a subset of the
310// Products to be successfully updated.
311func (c *ProductClient) ImportProducts(ctx context.Context, req *retailpb.ImportProductsRequest, opts ...gax.CallOption) (*ImportProductsOperation, error) {
312	if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines {
313		cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond)
314		defer cancel()
315		ctx = cctx
316	}
317	md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent())))
318	ctx = insertMetadata(ctx, c.xGoogMetadata, md)
319	opts = append(c.CallOptions.ImportProducts[0:len(c.CallOptions.ImportProducts):len(c.CallOptions.ImportProducts)], opts...)
320	var resp *longrunningpb.Operation
321	err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
322		var err error
323		resp, err = c.productClient.ImportProducts(ctx, req, settings.GRPC...)
324		return err
325	}, opts...)
326	if err != nil {
327		return nil, err
328	}
329	return &ImportProductsOperation{
330		lro: longrunning.InternalNewOperation(c.LROClient, resp),
331	}, nil
332}
333
334// ImportProductsOperation manages a long-running operation from ImportProducts.
335type ImportProductsOperation struct {
336	lro *longrunning.Operation
337}
338
339// ImportProductsOperation returns a new ImportProductsOperation from a given name.
340// The name must be that of a previously created ImportProductsOperation, possibly from a different process.
341func (c *ProductClient) ImportProductsOperation(name string) *ImportProductsOperation {
342	return &ImportProductsOperation{
343		lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}),
344	}
345}
346
347// Wait blocks until the long-running operation is completed, returning the response and any errors encountered.
348//
349// See documentation of Poll for error-handling information.
350func (op *ImportProductsOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*retailpb.ImportProductsResponse, error) {
351	var resp retailpb.ImportProductsResponse
352	if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil {
353		return nil, err
354	}
355	return &resp, nil
356}
357
358// Poll fetches the latest state of the long-running operation.
359//
360// Poll also fetches the latest metadata, which can be retrieved by Metadata.
361//
362// If Poll fails, the error is returned and op is unmodified. If Poll succeeds and
363// the operation has completed with failure, the error is returned and op.Done will return true.
364// If Poll succeeds and the operation has completed successfully,
365// op.Done will return true, and the response of the operation is returned.
366// If Poll succeeds and the operation has not completed, the returned response and error are both nil.
367func (op *ImportProductsOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*retailpb.ImportProductsResponse, error) {
368	var resp retailpb.ImportProductsResponse
369	if err := op.lro.Poll(ctx, &resp, opts...); err != nil {
370		return nil, err
371	}
372	if !op.Done() {
373		return nil, nil
374	}
375	return &resp, nil
376}
377
378// Metadata returns metadata associated with the long-running operation.
379// Metadata itself does not contact the server, but Poll does.
380// To get the latest metadata, call this method after a successful call to Poll.
381// If the metadata is not available, the returned metadata and error are both nil.
382func (op *ImportProductsOperation) Metadata() (*retailpb.ImportMetadata, error) {
383	var meta retailpb.ImportMetadata
384	if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata {
385		return nil, nil
386	} else if err != nil {
387		return nil, err
388	}
389	return &meta, nil
390}
391
392// Done reports whether the long-running operation has completed.
393func (op *ImportProductsOperation) Done() bool {
394	return op.lro.Done()
395}
396
397// Name returns the name of the long-running operation.
398// The name is assigned by the server and is unique within the service from which the operation is created.
399func (op *ImportProductsOperation) Name() string {
400	return op.lro.Name()
401}
402