Debian Codegraph @

shopping/merchant/products/apiv1/products_client.go

raw
1 // Copyright 2025 Google LLC
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 // Code generated by protoc-gen-go_gapic. DO NOT EDIT.
16
17 package products
18
19 import (
20 "context"
21 "fmt"
22 "log/slog"
23 "math"
24 "net/http"
25 "net/url"
26 "time"
27
28 productspb "cloud.google.com/go/shopping/merchant/products/apiv1/productspb"
29 gax "github.com/googleapis/gax-go/v2"
30 "google.golang.org/api/iterator"
31 "google.golang.org/api/option"
32 "google.golang.org/api/option/internaloption"
33 gtransport "google.golang.org/api/transport/grpc"
34 httptransport "google.golang.org/api/transport/http"
35 "google.golang.org/grpc"
36 "google.golang.org/grpc/codes"
37 "google.golang.org/protobuf/encoding/protojson"
38 "google.golang.org/protobuf/proto"
39 )
40
41 var newClientHook clientHook
42
43 // CallOptions contains the retry settings for each method of Client.
44 type CallOptions struct {
45 GetProduct []gax.CallOption
46 ListProducts []gax.CallOption
47 }
48
49 func defaultGRPCClientOptions() []option.ClientOption {
50 return []option.ClientOption{
51 internaloption.WithDefaultEndpoint("merchantapi.googleapis.com:443"),
52 internaloption.WithDefaultEndpointTemplate("merchantapi.UNIVERSE_DOMAIN:443"),
53 internaloption.WithDefaultMTLSEndpoint("merchantapi.mtls.googleapis.com:443"),
54 internaloption.WithDefaultUniverseDomain("googleapis.com"),
55 internaloption.WithDefaultAudience("https://merchantapi.googleapis.com/"),
56 internaloption.WithDefaultScopes(DefaultAuthScopes()...),
57 internaloption.EnableJwtWithScope(),
58 internaloption.EnableNewAuthLibrary(),
59 option.WithGRPCDialOption(grpc.WithDefaultCallOptions(
60 grpc.MaxCallRecvMsgSize(math.MaxInt32))),
61 }
62 }
63
64 func defaultCallOptions() *CallOptions {
65 return &CallOptions{
66 GetProduct: []gax.CallOption{
67 gax.WithTimeout(60000 * time.Millisecond),
68 gax.WithRetry(func() gax.Retryer {
69 return gax.OnCodes([]codes.Code{
70 codes.Unavailable,
71 }, gax.Backoff{
72 Initial: 1000 * time.Millisecond,
73 Max: 10000 * time.Millisecond,
74 Multiplier: 1.30,
75 })
76 }),
77 },
78 ListProducts: []gax.CallOption{
79 gax.WithTimeout(60000 * time.Millisecond),
80 gax.WithRetry(func() gax.Retryer {
81 return gax.OnCodes([]codes.Code{
82 codes.Unavailable,
83 }, gax.Backoff{
84 Initial: 1000 * time.Millisecond,
85 Max: 10000 * time.Millisecond,
86 Multiplier: 1.30,
87 })
88 }),
89 },
90 }
91 }
92
93 func defaultRESTCallOptions() *CallOptions {
94 return &CallOptions{
95 GetProduct: []gax.CallOption{
96 gax.WithTimeout(60000 * time.Millisecond),
97 gax.WithRetry(func() gax.Retryer {
98 return gax.OnHTTPCodes(gax.Backoff{
99 Initial: 1000 * time.Millisecond,
100 Max: 10000 * time.Millisecond,
101 Multiplier: 1.30,
102 },
103 http.StatusServiceUnavailable)
104 }),
105 },
106 ListProducts: []gax.CallOption{
107 gax.WithTimeout(60000 * time.Millisecond),
108 gax.WithRetry(func() gax.Retryer {
109 return gax.OnHTTPCodes(gax.Backoff{
110 Initial: 1000 * time.Millisecond,
111 Max: 10000 * time.Millisecond,
112 Multiplier: 1.30,
113 },
114 http.StatusServiceUnavailable)
115 }),
116 },
117 }
118 }
119
120 // internalClient is an interface that defines the methods available from Merchant API.
121 type internalClient interface {
122 Close() error
123 setGoogleClientInfo(...string)
124 Connection() *grpc.ClientConn
125 GetProduct(context.Context, *productspb.GetProductRequest, ...gax.CallOption) (*productspb.Product, error)
126 ListProducts(context.Context, *productspb.ListProductsRequest, ...gax.CallOption) *ProductIterator
127 }
128
129 // Client is a client for interacting with Merchant API.
130 // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls.
131 //
132 // Service to use Product resource.
133 type Client struct {
134 // The internal transport-dependent client.
135 internalClient internalClient
136
137 // The call options for this service.
138 CallOptions *CallOptions
139 }
140
141 // Wrapper methods routed to the internal client.
142
143 // Close closes the connection to the API service. The user should invoke this when
144 // the client is no longer required.
145 func (c *Client) Close() error {
146 return c.internalClient.Close()
147 }
148
149 // setGoogleClientInfo sets the name and version of the application in
150 // the `x-goog-api-client` header passed on each request. Intended for
151 // use by Google-written clients.
152 func (c *Client) setGoogleClientInfo(keyval ...string) {
153 c.internalClient.setGoogleClientInfo(keyval...)
154 }
155
156 // Connection returns a connection to the API service.
157 //
158 // Deprecated: Connections are now pooled so this method does not always
159 // return the same resource.
160 func (c *Client) Connection() *grpc.ClientConn {
161 return c.internalClient.Connection()
162 }
163
164 // GetProduct retrieves the processed product from your Merchant Center account.
165 //
166 // After inserting, updating, or deleting a product input, it may take several
167 // minutes before the updated final product can be retrieved.
168 func (c *Client) GetProduct(ctx context.Context, req *productspb.GetProductRequest, opts ...gax.CallOption) (*productspb.Product, error) {
169 return c.internalClient.GetProduct(ctx, req, opts...)
170 }
171
172 // ListProducts lists the processed products in your Merchant Center account. The response
173 // might contain fewer items than specified by pageSize. Rely on pageToken
174 // to determine if there are more items to be requested.
175 //
176 // After inserting, updating, or deleting a product input, it may take several
177 // minutes before the updated processed product can be retrieved.
178 func (c *Client) ListProducts(ctx context.Context, req *productspb.ListProductsRequest, opts ...gax.CallOption) *ProductIterator {
179 return c.internalClient.ListProducts(ctx, req, opts...)
180 }
181
182 // gRPCClient is a client for interacting with Merchant API over gRPC transport.
183 //
184 // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls.
185 type gRPCClient struct {
186 // Connection pool of gRPC connections to the service.
187 connPool gtransport.ConnPool
188
189 // Points back to the CallOptions field of the containing Client
190 CallOptions **CallOptions
191
192 // The gRPC API client.
193 client productspb.ProductsServiceClient
194
195 // The x-goog-* metadata to be sent with each request.
196 xGoogHeaders []string
197
198 logger *slog.Logger
199 }
200
201 // NewClient creates a new products service client based on gRPC.
202 // The returned client must be Closed when it is done being used to clean up its underlying connections.
203 //
204 // Service to use Product resource.
205 func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) {
206 clientOpts := defaultGRPCClientOptions()
207 if newClientHook != nil {
208 hookOpts, err := newClientHook(ctx, clientHookParams{})
209 if err != nil {
210 return nil, err
211 }
212 clientOpts = append(clientOpts, hookOpts...)
213 }
214
215 connPool, err := gtransport.DialPool(ctx, append(clientOpts, opts...)...)
216 if err != nil {
217 return nil, err
218 }
219 client := Client{CallOptions: defaultCallOptions()}
220
221 c := &gRPCClient{
222 connPool: connPool,
223 client: productspb.NewProductsServiceClient(connPool),
224 CallOptions: &client.CallOptions,
225 logger: internaloption.GetLogger(opts),
226 }
227 c.setGoogleClientInfo()
228
229 client.internalClient = c
230
231 return &client, nil
232 }
233
234 // Connection returns a connection to the API service.
235 //
236 // Deprecated: Connections are now pooled so this method does not always
237 // return the same resource.
238 func (c *gRPCClient) Connection() *grpc.ClientConn {
239 return c.connPool.Conn()
240 }
241
242 // setGoogleClientInfo sets the name and version of the application in
243 // the `x-goog-api-client` header passed on each request. Intended for
244 // use by Google-written clients.
245 func (c *gRPCClient) setGoogleClientInfo(keyval ...string) {
246 kv := append([]string{"gl-go", gax.GoVersion}, keyval...)
247 kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "grpc", grpc.Version, "pb", protoVersion)
248 c.xGoogHeaders = []string{
249 "x-goog-api-client", gax.XGoogHeader(kv...),
250 }
251 }
252
253 // Close closes the connection to the API service. The user should invoke this when
254 // the client is no longer required.
255 func (c *gRPCClient) Close() error {
256 return c.connPool.Close()
257 }
258
259 // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls.
260 type restClient struct {
261 // The http endpoint to connect to.
262 endpoint string
263
264 // The http client.
265 httpClient *http.Client
266
267 // The x-goog-* headers to be sent with each request.
268 xGoogHeaders []string
269
270 // Points back to the CallOptions field of the containing Client
271 CallOptions **CallOptions
272
273 logger *slog.Logger
274 }
275
276 // NewRESTClient creates a new products service rest client.
277 //
278 // Service to use Product resource.
279 func NewRESTClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) {
280 clientOpts := append(defaultRESTClientOptions(), opts...)
281 httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...)
282 if err != nil {
283 return nil, err
284 }
285
286 callOpts := defaultRESTCallOptions()
287 c := &restClient{
288 endpoint: endpoint,
289 httpClient: httpClient,
290 CallOptions: &callOpts,
291 logger: internaloption.GetLogger(opts),
292 }
293 c.setGoogleClientInfo()
294
295 return &Client{internalClient: c, CallOptions: callOpts}, nil
296 }
297
298 func defaultRESTClientOptions() []option.ClientOption {
299 return []option.ClientOption{
300 internaloption.WithDefaultEndpoint("https://merchantapi.googleapis.com"),
301 internaloption.WithDefaultEndpointTemplate("https://merchantapi.UNIVERSE_DOMAIN"),
302 internaloption.WithDefaultMTLSEndpoint("https://merchantapi.mtls.googleapis.com"),
303 internaloption.WithDefaultUniverseDomain("googleapis.com"),
304 internaloption.WithDefaultAudience("https://merchantapi.googleapis.com/"),
305 internaloption.WithDefaultScopes(DefaultAuthScopes()...),
306 internaloption.EnableNewAuthLibrary(),
307 }
308 }
309
310 // setGoogleClientInfo sets the name and version of the application in
311 // the `x-goog-api-client` header passed on each request. Intended for
312 // use by Google-written clients.
313 func (c *restClient) setGoogleClientInfo(keyval ...string) {
314 kv := append([]string{"gl-go", gax.GoVersion}, keyval...)
315 kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN", "pb", protoVersion)
316 c.xGoogHeaders = []string{
317 "x-goog-api-client", gax.XGoogHeader(kv...),
318 }
319 }
320
321 // Close closes the connection to the API service. The user should invoke this when
322 // the client is no longer required.
323 func (c *restClient) Close() error {
324 // Replace httpClient with nil to force cleanup.
325 c.httpClient = nil
326 return nil
327 }
328
329 // Connection returns a connection to the API service.
330 //
331 // Deprecated: This method always returns nil.
332 func (c *restClient) Connection() *grpc.ClientConn {
333 return nil
334 }
335 func (c *gRPCClient) GetProduct(ctx context.Context, req *productspb.GetProductRequest, opts ...gax.CallOption) (*productspb.Product, error) {
336 hds := []string{"x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))}
337
338 hds = append(c.xGoogHeaders, hds...)
339 ctx = gax.InsertMetadataIntoOutgoingContext(ctx, hds...)
340 opts = append((*c.CallOptions).GetProduct[0:len((*c.CallOptions).GetProduct):len((*c.CallOptions).GetProduct)], opts...)
341 var resp *productspb.Product
342 err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
343 var err error
344 resp, err = executeRPC(ctx, c.client.GetProduct, req, settings.GRPC, c.logger, "GetProduct")
345 return err
346 }, opts...)
347 if err != nil {
348 return nil, err
349 }
350 return resp, nil
351 }
352
353 func (c *gRPCClient) ListProducts(ctx context.Context, req *productspb.ListProductsRequest, opts ...gax.CallOption) *ProductIterator {
354 hds := []string{"x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))}
355
356 hds = append(c.xGoogHeaders, hds...)
357 ctx = gax.InsertMetadataIntoOutgoingContext(ctx, hds...)
358 opts = append((*c.CallOptions).ListProducts[0:len((*c.CallOptions).ListProducts):len((*c.CallOptions).ListProducts)], opts...)
359 it := &ProductIterator{}
360 req = proto.Clone(req).(*productspb.ListProductsRequest)
361 it.InternalFetch = func(pageSize int, pageToken string) ([]*productspb.Product, string, error) {
362 resp := &productspb.ListProductsResponse{}
363 if pageToken != "" {
364 req.PageToken = pageToken
365 }
366 if pageSize > math.MaxInt32 {
367 req.PageSize = math.MaxInt32
368 } else if pageSize != 0 {
369 req.PageSize = int32(pageSize)
370 }
371 err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
372 var err error
373 resp, err = executeRPC(ctx, c.client.ListProducts, req, settings.GRPC, c.logger, "ListProducts")
374 return err
375 }, opts...)
376 if err != nil {
377 return nil, "", err
378 }
379
380 it.Response = resp
381 return resp.GetProducts(), resp.GetNextPageToken(), nil
382 }
383 fetch := func(pageSize int, pageToken string) (string, error) {
384 items, nextPageToken, err := it.InternalFetch(pageSize, pageToken)
385 if err != nil {
386 return "", err
387 }
388 it.items = append(it.items, items...)
389 return nextPageToken, nil
390 }
391
392 it.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf)
393 it.pageInfo.MaxSize = int(req.GetPageSize())
394 it.pageInfo.Token = req.GetPageToken()
395
396 return it
397 }
398
399 // GetProduct retrieves the processed product from your Merchant Center account.
400 //
401 // After inserting, updating, or deleting a product input, it may take several
402 // minutes before the updated final product can be retrieved.
403 func (c *restClient) GetProduct(ctx context.Context, req *productspb.GetProductRequest, opts ...gax.CallOption) (*productspb.Product, error) {
404 baseUrl, err := url.Parse(c.endpoint)
405 if err != nil {
406 return nil, err
407 }
408 baseUrl.Path += fmt.Sprintf("/products/v1/%v", req.GetName())
409
410 params := url.Values{}
411 params.Add("$alt", "json;enum-encoding=int")
412
413 baseUrl.RawQuery = params.Encode()
414
415 // Build HTTP headers from client and context metadata.
416 hds := []string{"x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))}
417
418 hds = append(c.xGoogHeaders, hds...)
419 hds = append(hds, "Content-Type", "application/json")
420 headers := gax.BuildHeaders(ctx, hds...)
421 opts = append((*c.CallOptions).GetProduct[0:len((*c.CallOptions).GetProduct):len((*c.CallOptions).GetProduct)], opts...)
422 unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true}
423 resp := &productspb.Product{}
424 e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
425 if settings.Path != "" {
426 baseUrl.Path = settings.Path
427 }
428 httpReq, err := http.NewRequest("GET", baseUrl.String(), nil)
429 if err != nil {
430 return err
431 }
432 httpReq = httpReq.WithContext(ctx)
433 httpReq.Header = headers
434
435 buf, err := executeHTTPRequest(ctx, c.httpClient, httpReq, c.logger, nil, "GetProduct")
436 if err != nil {
437 return err
438 }
439
440 if err := unm.Unmarshal(buf, resp); err != nil {
441 return err
442 }
443
444 return nil
445 }, opts...)
446 if e != nil {
447 return nil, e
448 }
449 return resp, nil
450 }
451
452 // ListProducts lists the processed products in your Merchant Center account. The response
453 // might contain fewer items than specified by pageSize. Rely on pageToken
454 // to determine if there are more items to be requested.
455 //
456 // After inserting, updating, or deleting a product input, it may take several
457 // minutes before the updated processed product can be retrieved.
458 func (c *restClient) ListProducts(ctx context.Context, req *productspb.ListProductsRequest, opts ...gax.CallOption) *ProductIterator {
459 it := &ProductIterator{}
460 req = proto.Clone(req).(*productspb.ListProductsRequest)
461 unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true}
462 it.InternalFetch = func(pageSize int, pageToken string) ([]*productspb.Product, string, error) {
463 resp := &productspb.ListProductsResponse{}
464 if pageToken != "" {
465 req.PageToken = pageToken
466 }
467 if pageSize > math.MaxInt32 {
468 req.PageSize = math.MaxInt32
469 } else if pageSize != 0 {
470 req.PageSize = int32(pageSize)
471 }
472 baseUrl, err := url.Parse(c.endpoint)
473 if err != nil {
474 return nil, "", err
475 }
476 baseUrl.Path += fmt.Sprintf("/products/v1/%v/products", req.GetParent())
477
478 params := url.Values{}
479 params.Add("$alt", "json;enum-encoding=int")
480 if req.GetPageSize() != 0 {
481 params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize()))
482 }
483 if req.GetPageToken() != "" {
484 params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken()))
485 }
486
487 baseUrl.RawQuery = params.Encode()
488
489 // Build HTTP headers from client and context metadata.
490 hds := append(c.xGoogHeaders, "Content-Type", "application/json")
491 headers := gax.BuildHeaders(ctx, hds...)
492 e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
493 if settings.Path != "" {
494 baseUrl.Path = settings.Path
495 }
496 httpReq, err := http.NewRequest("GET", baseUrl.String(), nil)
497 if err != nil {
498 return err
499 }
500 httpReq.Header = headers
501
502 buf, err := executeHTTPRequest(ctx, c.httpClient, httpReq, c.logger, nil, "ListProducts")
503 if err != nil {
504 return err
505 }
506 if err := unm.Unmarshal(buf, resp); err != nil {
507 return err
508 }
509
510 return nil
511 }, opts...)
512 if e != nil {
513 return nil, "", e
514 }
515 it.Response = resp
516 return resp.GetProducts(), resp.GetNextPageToken(), nil
517 }
518
519 fetch := func(pageSize int, pageToken string) (string, error) {
520 items, nextPageToken, err := it.InternalFetch(pageSize, pageToken)
521 if err != nil {
522 return "", err
523 }
524 it.items = append(it.items, items...)
525 return nextPageToken, nil
526 }
527
528 it.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf)
529 it.pageInfo.MaxSize = int(req.GetPageSize())
530 it.pageInfo.Token = req.GetPageToken()
531
532 return it
533 }