Debian Codegraph @

shopping/merchant/reports/apiv1/report_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 reports
18
19 import (
20 "bytes"
21 "context"
22 "fmt"
23 "log/slog"
24 "math"
25 "net/http"
26 "net/url"
27 "time"
28
29 reportspb "cloud.google.com/go/shopping/merchant/reports/apiv1/reportspb"
30 gax "github.com/googleapis/gax-go/v2"
31 "google.golang.org/api/iterator"
32 "google.golang.org/api/option"
33 "google.golang.org/api/option/internaloption"
34 gtransport "google.golang.org/api/transport/grpc"
35 httptransport "google.golang.org/api/transport/http"
36 "google.golang.org/grpc"
37 "google.golang.org/grpc/codes"
38 "google.golang.org/protobuf/encoding/protojson"
39 "google.golang.org/protobuf/proto"
40 )
41
42 var newReportClientHook clientHook
43
44 // ReportCallOptions contains the retry settings for each method of ReportClient.
45 type ReportCallOptions struct {
46 Search []gax.CallOption
47 }
48
49 func defaultReportGRPCClientOptions() []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 defaultReportCallOptions() *ReportCallOptions {
65 return &ReportCallOptions{
66 Search: []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 }
79 }
80
81 func defaultReportRESTCallOptions() *ReportCallOptions {
82 return &ReportCallOptions{
83 Search: []gax.CallOption{
84 gax.WithTimeout(60000 * time.Millisecond),
85 gax.WithRetry(func() gax.Retryer {
86 return gax.OnHTTPCodes(gax.Backoff{
87 Initial: 1000 * time.Millisecond,
88 Max: 10000 * time.Millisecond,
89 Multiplier: 1.30,
90 },
91 http.StatusServiceUnavailable)
92 }),
93 },
94 }
95 }
96
97 // internalReportClient is an interface that defines the methods available from Merchant API.
98 type internalReportClient interface {
99 Close() error
100 setGoogleClientInfo(...string)
101 Connection() *grpc.ClientConn
102 Search(context.Context, *reportspb.SearchRequest, ...gax.CallOption) *ReportRowIterator
103 }
104
105 // ReportClient is a client for interacting with Merchant API.
106 // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls.
107 //
108 // Service for retrieving reports and insights about your products, their
109 // performance, and their competitive environment on Google.
110 type ReportClient struct {
111 // The internal transport-dependent client.
112 internalClient internalReportClient
113
114 // The call options for this service.
115 CallOptions *ReportCallOptions
116 }
117
118 // Wrapper methods routed to the internal client.
119
120 // Close closes the connection to the API service. The user should invoke this when
121 // the client is no longer required.
122 func (c *ReportClient) Close() error {
123 return c.internalClient.Close()
124 }
125
126 // setGoogleClientInfo sets the name and version of the application in
127 // the `x-goog-api-client` header passed on each request. Intended for
128 // use by Google-written clients.
129 func (c *ReportClient) setGoogleClientInfo(keyval ...string) {
130 c.internalClient.setGoogleClientInfo(keyval...)
131 }
132
133 // Connection returns a connection to the API service.
134 //
135 // Deprecated: Connections are now pooled so this method does not always
136 // return the same resource.
137 func (c *ReportClient) Connection() *grpc.ClientConn {
138 return c.internalClient.Connection()
139 }
140
141 // Search retrieves a report defined by a search query. The response might contain
142 // fewer rows than specified by page_size. Rely on next_page_token to
143 // determine if there are more rows to be requested.
144 func (c *ReportClient) Search(ctx context.Context, req *reportspb.SearchRequest, opts ...gax.CallOption) *ReportRowIterator {
145 return c.internalClient.Search(ctx, req, opts...)
146 }
147
148 // reportGRPCClient is a client for interacting with Merchant API over gRPC transport.
149 //
150 // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls.
151 type reportGRPCClient struct {
152 // Connection pool of gRPC connections to the service.
153 connPool gtransport.ConnPool
154
155 // Points back to the CallOptions field of the containing ReportClient
156 CallOptions **ReportCallOptions
157
158 // The gRPC API client.
159 reportClient reportspb.ReportServiceClient
160
161 // The x-goog-* metadata to be sent with each request.
162 xGoogHeaders []string
163
164 logger *slog.Logger
165 }
166
167 // NewReportClient creates a new report service client based on gRPC.
168 // The returned client must be Closed when it is done being used to clean up its underlying connections.
169 //
170 // Service for retrieving reports and insights about your products, their
171 // performance, and their competitive environment on Google.
172 func NewReportClient(ctx context.Context, opts ...option.ClientOption) (*ReportClient, error) {
173 clientOpts := defaultReportGRPCClientOptions()
174 if newReportClientHook != nil {
175 hookOpts, err := newReportClientHook(ctx, clientHookParams{})
176 if err != nil {
177 return nil, err
178 }
179 clientOpts = append(clientOpts, hookOpts...)
180 }
181
182 connPool, err := gtransport.DialPool(ctx, append(clientOpts, opts...)...)
183 if err != nil {
184 return nil, err
185 }
186 client := ReportClient{CallOptions: defaultReportCallOptions()}
187
188 c := &reportGRPCClient{
189 connPool: connPool,
190 reportClient: reportspb.NewReportServiceClient(connPool),
191 CallOptions: &client.CallOptions,
192 logger: internaloption.GetLogger(opts),
193 }
194 c.setGoogleClientInfo()
195
196 client.internalClient = c
197
198 return &client, nil
199 }
200
201 // Connection returns a connection to the API service.
202 //
203 // Deprecated: Connections are now pooled so this method does not always
204 // return the same resource.
205 func (c *reportGRPCClient) Connection() *grpc.ClientConn {
206 return c.connPool.Conn()
207 }
208
209 // setGoogleClientInfo sets the name and version of the application in
210 // the `x-goog-api-client` header passed on each request. Intended for
211 // use by Google-written clients.
212 func (c *reportGRPCClient) setGoogleClientInfo(keyval ...string) {
213 kv := append([]string{"gl-go", gax.GoVersion}, keyval...)
214 kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "grpc", grpc.Version, "pb", protoVersion)
215 c.xGoogHeaders = []string{
216 "x-goog-api-client", gax.XGoogHeader(kv...),
217 }
218 }
219
220 // Close closes the connection to the API service. The user should invoke this when
221 // the client is no longer required.
222 func (c *reportGRPCClient) Close() error {
223 return c.connPool.Close()
224 }
225
226 // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls.
227 type reportRESTClient struct {
228 // The http endpoint to connect to.
229 endpoint string
230
231 // The http client.
232 httpClient *http.Client
233
234 // The x-goog-* headers to be sent with each request.
235 xGoogHeaders []string
236
237 // Points back to the CallOptions field of the containing ReportClient
238 CallOptions **ReportCallOptions
239
240 logger *slog.Logger
241 }
242
243 // NewReportRESTClient creates a new report service rest client.
244 //
245 // Service for retrieving reports and insights about your products, their
246 // performance, and their competitive environment on Google.
247 func NewReportRESTClient(ctx context.Context, opts ...option.ClientOption) (*ReportClient, error) {
248 clientOpts := append(defaultReportRESTClientOptions(), opts...)
249 httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...)
250 if err != nil {
251 return nil, err
252 }
253
254 callOpts := defaultReportRESTCallOptions()
255 c := &reportRESTClient{
256 endpoint: endpoint,
257 httpClient: httpClient,
258 CallOptions: &callOpts,
259 logger: internaloption.GetLogger(opts),
260 }
261 c.setGoogleClientInfo()
262
263 return &ReportClient{internalClient: c, CallOptions: callOpts}, nil
264 }
265
266 func defaultReportRESTClientOptions() []option.ClientOption {
267 return []option.ClientOption{
268 internaloption.WithDefaultEndpoint("https://merchantapi.googleapis.com"),
269 internaloption.WithDefaultEndpointTemplate("https://merchantapi.UNIVERSE_DOMAIN"),
270 internaloption.WithDefaultMTLSEndpoint("https://merchantapi.mtls.googleapis.com"),
271 internaloption.WithDefaultUniverseDomain("googleapis.com"),
272 internaloption.WithDefaultAudience("https://merchantapi.googleapis.com/"),
273 internaloption.WithDefaultScopes(DefaultAuthScopes()...),
274 internaloption.EnableNewAuthLibrary(),
275 }
276 }
277
278 // setGoogleClientInfo sets the name and version of the application in
279 // the `x-goog-api-client` header passed on each request. Intended for
280 // use by Google-written clients.
281 func (c *reportRESTClient) setGoogleClientInfo(keyval ...string) {
282 kv := append([]string{"gl-go", gax.GoVersion}, keyval...)
283 kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN", "pb", protoVersion)
284 c.xGoogHeaders = []string{
285 "x-goog-api-client", gax.XGoogHeader(kv...),
286 }
287 }
288
289 // Close closes the connection to the API service. The user should invoke this when
290 // the client is no longer required.
291 func (c *reportRESTClient) Close() error {
292 // Replace httpClient with nil to force cleanup.
293 c.httpClient = nil
294 return nil
295 }
296
297 // Connection returns a connection to the API service.
298 //
299 // Deprecated: This method always returns nil.
300 func (c *reportRESTClient) Connection() *grpc.ClientConn {
301 return nil
302 }
303 func (c *reportGRPCClient) Search(ctx context.Context, req *reportspb.SearchRequest, opts ...gax.CallOption) *ReportRowIterator {
304 hds := []string{"x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))}
305
306 hds = append(c.xGoogHeaders, hds...)
307 ctx = gax.InsertMetadataIntoOutgoingContext(ctx, hds...)
308 opts = append((*c.CallOptions).Search[0:len((*c.CallOptions).Search):len((*c.CallOptions).Search)], opts...)
309 it := &ReportRowIterator{}
310 req = proto.Clone(req).(*reportspb.SearchRequest)
311 it.InternalFetch = func(pageSize int, pageToken string) ([]*reportspb.ReportRow, string, error) {
312 resp := &reportspb.SearchResponse{}
313 if pageToken != "" {
314 req.PageToken = pageToken
315 }
316 if pageSize > math.MaxInt32 {
317 req.PageSize = math.MaxInt32
318 } else if pageSize != 0 {
319 req.PageSize = int32(pageSize)
320 }
321 err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
322 var err error
323 resp, err = executeRPC(ctx, c.reportClient.Search, req, settings.GRPC, c.logger, "Search")
324 return err
325 }, opts...)
326 if err != nil {
327 return nil, "", err
328 }
329
330 it.Response = resp
331 return resp.GetResults(), resp.GetNextPageToken(), nil
332 }
333 fetch := func(pageSize int, pageToken string) (string, error) {
334 items, nextPageToken, err := it.InternalFetch(pageSize, pageToken)
335 if err != nil {
336 return "", err
337 }
338 it.items = append(it.items, items...)
339 return nextPageToken, nil
340 }
341
342 it.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf)
343 it.pageInfo.MaxSize = int(req.GetPageSize())
344 it.pageInfo.Token = req.GetPageToken()
345
346 return it
347 }
348
349 // Search retrieves a report defined by a search query. The response might contain
350 // fewer rows than specified by page_size. Rely on next_page_token to
351 // determine if there are more rows to be requested.
352 func (c *reportRESTClient) Search(ctx context.Context, req *reportspb.SearchRequest, opts ...gax.CallOption) *ReportRowIterator {
353 it := &ReportRowIterator{}
354 req = proto.Clone(req).(*reportspb.SearchRequest)
355 m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true}
356 unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true}
357 it.InternalFetch = func(pageSize int, pageToken string) ([]*reportspb.ReportRow, string, error) {
358 resp := &reportspb.SearchResponse{}
359 if pageToken != "" {
360 req.PageToken = pageToken
361 }
362 if pageSize > math.MaxInt32 {
363 req.PageSize = math.MaxInt32
364 } else if pageSize != 0 {
365 req.PageSize = int32(pageSize)
366 }
367 jsonReq, err := m.Marshal(req)
368 if err != nil {
369 return nil, "", err
370 }
371
372 baseUrl, err := url.Parse(c.endpoint)
373 if err != nil {
374 return nil, "", err
375 }
376 baseUrl.Path += fmt.Sprintf("/reports/v1/%v/reports:search", req.GetParent())
377
378 params := url.Values{}
379 params.Add("$alt", "json;enum-encoding=int")
380
381 baseUrl.RawQuery = params.Encode()
382
383 // Build HTTP headers from client and context metadata.
384 hds := append(c.xGoogHeaders, "Content-Type", "application/json")
385 headers := gax.BuildHeaders(ctx, hds...)
386 e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
387 if settings.Path != "" {
388 baseUrl.Path = settings.Path
389 }
390 httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq))
391 if err != nil {
392 return err
393 }
394 httpReq.Header = headers
395
396 buf, err := executeHTTPRequest(ctx, c.httpClient, httpReq, c.logger, jsonReq, "Search")
397 if err != nil {
398 return err
399 }
400 if err := unm.Unmarshal(buf, resp); err != nil {
401 return err
402 }
403
404 return nil
405 }, opts...)
406 if e != nil {
407 return nil, "", e
408 }
409 it.Response = resp
410 return resp.GetResults(), resp.GetNextPageToken(), nil
411 }
412
413 fetch := func(pageSize int, pageToken string) (string, error) {
414 items, nextPageToken, err := it.InternalFetch(pageSize, pageToken)
415 if err != nil {
416 return "", err
417 }
418 it.items = append(it.items, items...)
419 return nextPageToken, nil
420 }
421
422 it.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf)
423 it.pageInfo.MaxSize = int(req.GetPageSize())
424 it.pageInfo.Token = req.GetPageToken()
425
426 return it
427 }