1// Copyright 2020 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 cloudtasks
18
19import (
20	"context"
21	"fmt"
22	"math"
23	"net/url"
24	"time"
25
26	"github.com/golang/protobuf/proto"
27	gax "github.com/googleapis/gax-go/v2"
28	"google.golang.org/api/iterator"
29	"google.golang.org/api/option"
30	gtransport "google.golang.org/api/transport/grpc"
31	taskspb "google.golang.org/genproto/googleapis/cloud/tasks/v2"
32	iampb "google.golang.org/genproto/googleapis/iam/v1"
33	"google.golang.org/grpc"
34	"google.golang.org/grpc/codes"
35	"google.golang.org/grpc/metadata"
36)
37
38var newClientHook clientHook
39
40// CallOptions contains the retry settings for each method of Client.
41type CallOptions struct {
42	ListQueues         []gax.CallOption
43	GetQueue           []gax.CallOption
44	CreateQueue        []gax.CallOption
45	UpdateQueue        []gax.CallOption
46	DeleteQueue        []gax.CallOption
47	PurgeQueue         []gax.CallOption
48	PauseQueue         []gax.CallOption
49	ResumeQueue        []gax.CallOption
50	GetIamPolicy       []gax.CallOption
51	SetIamPolicy       []gax.CallOption
52	TestIamPermissions []gax.CallOption
53	ListTasks          []gax.CallOption
54	GetTask            []gax.CallOption
55	CreateTask         []gax.CallOption
56	DeleteTask         []gax.CallOption
57	RunTask            []gax.CallOption
58}
59
60func defaultClientOptions() []option.ClientOption {
61	return []option.ClientOption{
62		option.WithEndpoint("cloudtasks.googleapis.com:443"),
63		option.WithGRPCDialOption(grpc.WithDisableServiceConfig()),
64		option.WithScopes(DefaultAuthScopes()...),
65		option.WithGRPCDialOption(grpc.WithDefaultCallOptions(
66			grpc.MaxCallRecvMsgSize(math.MaxInt32))),
67	}
68}
69
70func defaultCallOptions() *CallOptions {
71	return &CallOptions{
72		ListQueues: []gax.CallOption{
73			gax.WithRetry(func() gax.Retryer {
74				return gax.OnCodes([]codes.Code{
75					codes.DeadlineExceeded,
76					codes.Unavailable,
77				}, gax.Backoff{
78					Initial:    100 * time.Millisecond,
79					Max:        10000 * time.Millisecond,
80					Multiplier: 1.30,
81				})
82			}),
83		},
84		GetQueue: []gax.CallOption{
85			gax.WithRetry(func() gax.Retryer {
86				return gax.OnCodes([]codes.Code{
87					codes.DeadlineExceeded,
88					codes.Unavailable,
89				}, gax.Backoff{
90					Initial:    100 * time.Millisecond,
91					Max:        10000 * time.Millisecond,
92					Multiplier: 1.30,
93				})
94			}),
95		},
96		CreateQueue: []gax.CallOption{},
97		UpdateQueue: []gax.CallOption{},
98		DeleteQueue: []gax.CallOption{
99			gax.WithRetry(func() gax.Retryer {
100				return gax.OnCodes([]codes.Code{
101					codes.DeadlineExceeded,
102					codes.Unavailable,
103				}, gax.Backoff{
104					Initial:    100 * time.Millisecond,
105					Max:        10000 * time.Millisecond,
106					Multiplier: 1.30,
107				})
108			}),
109		},
110		PurgeQueue:  []gax.CallOption{},
111		PauseQueue:  []gax.CallOption{},
112		ResumeQueue: []gax.CallOption{},
113		GetIamPolicy: []gax.CallOption{
114			gax.WithRetry(func() gax.Retryer {
115				return gax.OnCodes([]codes.Code{
116					codes.DeadlineExceeded,
117					codes.Unavailable,
118				}, gax.Backoff{
119					Initial:    100 * time.Millisecond,
120					Max:        10000 * time.Millisecond,
121					Multiplier: 1.30,
122				})
123			}),
124		},
125		SetIamPolicy: []gax.CallOption{},
126		TestIamPermissions: []gax.CallOption{
127			gax.WithRetry(func() gax.Retryer {
128				return gax.OnCodes([]codes.Code{
129					codes.DeadlineExceeded,
130					codes.Unavailable,
131				}, gax.Backoff{
132					Initial:    100 * time.Millisecond,
133					Max:        10000 * time.Millisecond,
134					Multiplier: 1.30,
135				})
136			}),
137		},
138		ListTasks: []gax.CallOption{
139			gax.WithRetry(func() gax.Retryer {
140				return gax.OnCodes([]codes.Code{
141					codes.DeadlineExceeded,
142					codes.Unavailable,
143				}, gax.Backoff{
144					Initial:    100 * time.Millisecond,
145					Max:        10000 * time.Millisecond,
146					Multiplier: 1.30,
147				})
148			}),
149		},
150		GetTask: []gax.CallOption{
151			gax.WithRetry(func() gax.Retryer {
152				return gax.OnCodes([]codes.Code{
153					codes.DeadlineExceeded,
154					codes.Unavailable,
155				}, gax.Backoff{
156					Initial:    100 * time.Millisecond,
157					Max:        10000 * time.Millisecond,
158					Multiplier: 1.30,
159				})
160			}),
161		},
162		CreateTask: []gax.CallOption{},
163		DeleteTask: []gax.CallOption{
164			gax.WithRetry(func() gax.Retryer {
165				return gax.OnCodes([]codes.Code{
166					codes.DeadlineExceeded,
167					codes.Unavailable,
168				}, gax.Backoff{
169					Initial:    100 * time.Millisecond,
170					Max:        10000 * time.Millisecond,
171					Multiplier: 1.30,
172				})
173			}),
174		},
175		RunTask: []gax.CallOption{},
176	}
177}
178
179// Client is a client for interacting with Cloud Tasks API.
180//
181// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls.
182type Client struct {
183	// Connection pool of gRPC connections to the service.
184	connPool gtransport.ConnPool
185
186	// flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE
187	disableDeadlines bool
188
189	// The gRPC API client.
190	client taskspb.CloudTasksClient
191
192	// The call options for this service.
193	CallOptions *CallOptions
194
195	// The x-goog-* metadata to be sent with each request.
196	xGoogMetadata metadata.MD
197}
198
199// NewClient creates a new cloud tasks client.
200//
201// Cloud Tasks allows developers to manage the execution of background
202// work in their applications.
203func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) {
204	clientOpts := defaultClientOptions()
205
206	if newClientHook != nil {
207		hookOpts, err := newClientHook(ctx, clientHookParams{})
208		if err != nil {
209			return nil, err
210		}
211		clientOpts = append(clientOpts, hookOpts...)
212	}
213
214	disableDeadlines, err := checkDisableDeadlines()
215	if err != nil {
216		return nil, err
217	}
218
219	connPool, err := gtransport.DialPool(ctx, append(clientOpts, opts...)...)
220	if err != nil {
221		return nil, err
222	}
223	c := &Client{
224		connPool:         connPool,
225		disableDeadlines: disableDeadlines,
226		CallOptions:      defaultCallOptions(),
227
228		client: taskspb.NewCloudTasksClient(connPool),
229	}
230	c.setGoogleClientInfo()
231
232	return c, nil
233}
234
235// Connection returns a connection to the API service.
236//
237// Deprecated.
238func (c *Client) Connection() *grpc.ClientConn {
239	return c.connPool.Conn()
240}
241
242// Close closes the connection to the API service. The user should invoke this when
243// the client is no longer required.
244func (c *Client) Close() error {
245	return c.connPool.Close()
246}
247
248// setGoogleClientInfo sets the name and version of the application in
249// the `x-goog-api-client` header passed on each request. Intended for
250// use by Google-written clients.
251func (c *Client) setGoogleClientInfo(keyval ...string) {
252	kv := append([]string{"gl-go", versionGo()}, keyval...)
253	kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version)
254	c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...))
255}
256
257// ListQueues lists queues.
258//
259// Queues are returned in lexicographical order.
260func (c *Client) ListQueues(ctx context.Context, req *taskspb.ListQueuesRequest, opts ...gax.CallOption) *QueueIterator {
261	md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent())))
262	ctx = insertMetadata(ctx, c.xGoogMetadata, md)
263	opts = append(c.CallOptions.ListQueues[0:len(c.CallOptions.ListQueues):len(c.CallOptions.ListQueues)], opts...)
264	it := &QueueIterator{}
265	req = proto.Clone(req).(*taskspb.ListQueuesRequest)
266	it.InternalFetch = func(pageSize int, pageToken string) ([]*taskspb.Queue, string, error) {
267		var resp *taskspb.ListQueuesResponse
268		req.PageToken = pageToken
269		if pageSize > math.MaxInt32 {
270			req.PageSize = math.MaxInt32
271		} else {
272			req.PageSize = int32(pageSize)
273		}
274		err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
275			var err error
276			resp, err = c.client.ListQueues(ctx, req, settings.GRPC...)
277			return err
278		}, opts...)
279		if err != nil {
280			return nil, "", err
281		}
282
283		it.Response = resp
284		return resp.GetQueues(), resp.GetNextPageToken(), nil
285	}
286	fetch := func(pageSize int, pageToken string) (string, error) {
287		items, nextPageToken, err := it.InternalFetch(pageSize, pageToken)
288		if err != nil {
289			return "", err
290		}
291		it.items = append(it.items, items...)
292		return nextPageToken, nil
293	}
294	it.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf)
295	it.pageInfo.MaxSize = int(req.GetPageSize())
296	it.pageInfo.Token = req.GetPageToken()
297	return it
298}
299
300// GetQueue gets a queue.
301func (c *Client) GetQueue(ctx context.Context, req *taskspb.GetQueueRequest, opts ...gax.CallOption) (*taskspb.Queue, error) {
302	if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines {
303		cctx, cancel := context.WithTimeout(ctx, 10000*time.Millisecond)
304		defer cancel()
305		ctx = cctx
306	}
307	md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName())))
308	ctx = insertMetadata(ctx, c.xGoogMetadata, md)
309	opts = append(c.CallOptions.GetQueue[0:len(c.CallOptions.GetQueue):len(c.CallOptions.GetQueue)], opts...)
310	var resp *taskspb.Queue
311	err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
312		var err error
313		resp, err = c.client.GetQueue(ctx, req, settings.GRPC...)
314		return err
315	}, opts...)
316	if err != nil {
317		return nil, err
318	}
319	return resp, nil
320}
321
322// CreateQueue creates a queue.
323//
324// Queues created with this method allow tasks to live for a maximum of 31
325// days. After a task is 31 days old, the task will be deleted regardless of whether
326// it was dispatched or not.
327//
328// WARNING: Using this method may have unintended side effects if you are
329// using an App Engine queue.yaml or queue.xml file to manage your queues.
330// Read
331// Overview of Queue Management and
332// queue.yaml (at https://cloud.google.com/tasks/docs/queue-yaml) before using
333// this method.
334func (c *Client) CreateQueue(ctx context.Context, req *taskspb.CreateQueueRequest, opts ...gax.CallOption) (*taskspb.Queue, error) {
335	if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines {
336		cctx, cancel := context.WithTimeout(ctx, 10000*time.Millisecond)
337		defer cancel()
338		ctx = cctx
339	}
340	md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent())))
341	ctx = insertMetadata(ctx, c.xGoogMetadata, md)
342	opts = append(c.CallOptions.CreateQueue[0:len(c.CallOptions.CreateQueue):len(c.CallOptions.CreateQueue)], opts...)
343	var resp *taskspb.Queue
344	err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
345		var err error
346		resp, err = c.client.CreateQueue(ctx, req, settings.GRPC...)
347		return err
348	}, opts...)
349	if err != nil {
350		return nil, err
351	}
352	return resp, nil
353}
354
355// UpdateQueue updates a queue.
356//
357// This method creates the queue if it does not exist and updates
358// the queue if it does exist.
359//
360// Queues created with this method allow tasks to live for a maximum of 31
361// days. After a task is 31 days old, the task will be deleted regardless of whether
362// it was dispatched or not.
363//
364// WARNING: Using this method may have unintended side effects if you are
365// using an App Engine queue.yaml or queue.xml file to manage your queues.
366// Read
367// Overview of Queue Management and
368// queue.yaml (at https://cloud.google.com/tasks/docs/queue-yaml) before using
369// this method.
370func (c *Client) UpdateQueue(ctx context.Context, req *taskspb.UpdateQueueRequest, opts ...gax.CallOption) (*taskspb.Queue, error) {
371	if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines {
372		cctx, cancel := context.WithTimeout(ctx, 10000*time.Millisecond)
373		defer cancel()
374		ctx = cctx
375	}
376	md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "queue.name", url.QueryEscape(req.GetQueue().GetName())))
377	ctx = insertMetadata(ctx, c.xGoogMetadata, md)
378	opts = append(c.CallOptions.UpdateQueue[0:len(c.CallOptions.UpdateQueue):len(c.CallOptions.UpdateQueue)], opts...)
379	var resp *taskspb.Queue
380	err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
381		var err error
382		resp, err = c.client.UpdateQueue(ctx, req, settings.GRPC...)
383		return err
384	}, opts...)
385	if err != nil {
386		return nil, err
387	}
388	return resp, nil
389}
390
391// DeleteQueue deletes a queue.
392//
393// This command will delete the queue even if it has tasks in it.
394//
395// Note: If you delete a queue, a queue with the same name can’t be created
396// for 7 days.
397//
398// WARNING: Using this method may have unintended side effects if you are
399// using an App Engine queue.yaml or queue.xml file to manage your queues.
400// Read
401// Overview of Queue Management and
402// queue.yaml (at https://cloud.google.com/tasks/docs/queue-yaml) before using
403// this method.
404func (c *Client) DeleteQueue(ctx context.Context, req *taskspb.DeleteQueueRequest, opts ...gax.CallOption) error {
405	if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines {
406		cctx, cancel := context.WithTimeout(ctx, 10000*time.Millisecond)
407		defer cancel()
408		ctx = cctx
409	}
410	md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName())))
411	ctx = insertMetadata(ctx, c.xGoogMetadata, md)
412	opts = append(c.CallOptions.DeleteQueue[0:len(c.CallOptions.DeleteQueue):len(c.CallOptions.DeleteQueue)], opts...)
413	err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
414		var err error
415		_, err = c.client.DeleteQueue(ctx, req, settings.GRPC...)
416		return err
417	}, opts...)
418	return err
419}
420
421// PurgeQueue purges a queue by deleting all of its tasks.
422//
423// All tasks created before this method is called are permanently deleted.
424//
425// Purge operations can take up to one minute to take effect. Tasks
426// might be dispatched before the purge takes effect. A purge is irreversible.
427func (c *Client) PurgeQueue(ctx context.Context, req *taskspb.PurgeQueueRequest, opts ...gax.CallOption) (*taskspb.Queue, error) {
428	if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines {
429		cctx, cancel := context.WithTimeout(ctx, 10000*time.Millisecond)
430		defer cancel()
431		ctx = cctx
432	}
433	md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName())))
434	ctx = insertMetadata(ctx, c.xGoogMetadata, md)
435	opts = append(c.CallOptions.PurgeQueue[0:len(c.CallOptions.PurgeQueue):len(c.CallOptions.PurgeQueue)], opts...)
436	var resp *taskspb.Queue
437	err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
438		var err error
439		resp, err = c.client.PurgeQueue(ctx, req, settings.GRPC...)
440		return err
441	}, opts...)
442	if err != nil {
443		return nil, err
444	}
445	return resp, nil
446}
447
448// PauseQueue pauses the queue.
449//
450// If a queue is paused then the system will stop dispatching tasks
451// until the queue is resumed via
452// ResumeQueue. Tasks can still be added
453// when the queue is paused. A queue is paused if its
454// state is PAUSED.
455func (c *Client) PauseQueue(ctx context.Context, req *taskspb.PauseQueueRequest, opts ...gax.CallOption) (*taskspb.Queue, error) {
456	if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines {
457		cctx, cancel := context.WithTimeout(ctx, 10000*time.Millisecond)
458		defer cancel()
459		ctx = cctx
460	}
461	md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName())))
462	ctx = insertMetadata(ctx, c.xGoogMetadata, md)
463	opts = append(c.CallOptions.PauseQueue[0:len(c.CallOptions.PauseQueue):len(c.CallOptions.PauseQueue)], opts...)
464	var resp *taskspb.Queue
465	err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
466		var err error
467		resp, err = c.client.PauseQueue(ctx, req, settings.GRPC...)
468		return err
469	}, opts...)
470	if err != nil {
471		return nil, err
472	}
473	return resp, nil
474}
475
476// ResumeQueue resume a queue.
477//
478// This method resumes a queue after it has been
479// PAUSED or
480// DISABLED. The state of a queue is stored
481// in the queue’s state; after calling this method it
482// will be set to RUNNING.
483//
484// WARNING: Resuming many high-QPS queues at the same time can
485// lead to target overloading. If you are resuming high-QPS
486// queues, follow the 500/50/5 pattern described in
487// Managing Cloud Tasks Scaling
488// Risks (at https://cloud.google.com/tasks/docs/manage-cloud-task-scaling).
489func (c *Client) ResumeQueue(ctx context.Context, req *taskspb.ResumeQueueRequest, opts ...gax.CallOption) (*taskspb.Queue, error) {
490	if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines {
491		cctx, cancel := context.WithTimeout(ctx, 10000*time.Millisecond)
492		defer cancel()
493		ctx = cctx
494	}
495	md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName())))
496	ctx = insertMetadata(ctx, c.xGoogMetadata, md)
497	opts = append(c.CallOptions.ResumeQueue[0:len(c.CallOptions.ResumeQueue):len(c.CallOptions.ResumeQueue)], opts...)
498	var resp *taskspb.Queue
499	err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
500		var err error
501		resp, err = c.client.ResumeQueue(ctx, req, settings.GRPC...)
502		return err
503	}, opts...)
504	if err != nil {
505		return nil, err
506	}
507	return resp, nil
508}
509
510// GetIamPolicy gets the access control policy for a Queue.
511// Returns an empty policy if the resource exists and does not have a policy
512// set.
513//
514// Authorization requires the following
515// Google IAM (at https://cloud.google.com/iam) permission on the specified
516// resource parent:
517//
518//   cloudtasks.queues.getIamPolicy
519func (c *Client) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) {
520	if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines {
521		cctx, cancel := context.WithTimeout(ctx, 10000*time.Millisecond)
522		defer cancel()
523		ctx = cctx
524	}
525	md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource())))
526	ctx = insertMetadata(ctx, c.xGoogMetadata, md)
527	opts = append(c.CallOptions.GetIamPolicy[0:len(c.CallOptions.GetIamPolicy):len(c.CallOptions.GetIamPolicy)], opts...)
528	var resp *iampb.Policy
529	err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
530		var err error
531		resp, err = c.client.GetIamPolicy(ctx, req, settings.GRPC...)
532		return err
533	}, opts...)
534	if err != nil {
535		return nil, err
536	}
537	return resp, nil
538}
539
540// SetIamPolicy sets the access control policy for a Queue. Replaces any existing
541// policy.
542//
543// Note: The Cloud Console does not check queue-level IAM permissions yet.
544// Project-level permissions are required to use the Cloud Console.
545//
546// Authorization requires the following
547// Google IAM (at https://cloud.google.com/iam) permission on the specified
548// resource parent:
549//
550//   cloudtasks.queues.setIamPolicy
551func (c *Client) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) {
552	if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines {
553		cctx, cancel := context.WithTimeout(ctx, 10000*time.Millisecond)
554		defer cancel()
555		ctx = cctx
556	}
557	md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource())))
558	ctx = insertMetadata(ctx, c.xGoogMetadata, md)
559	opts = append(c.CallOptions.SetIamPolicy[0:len(c.CallOptions.SetIamPolicy):len(c.CallOptions.SetIamPolicy)], opts...)
560	var resp *iampb.Policy
561	err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
562		var err error
563		resp, err = c.client.SetIamPolicy(ctx, req, settings.GRPC...)
564		return err
565	}, opts...)
566	if err != nil {
567		return nil, err
568	}
569	return resp, nil
570}
571
572// TestIamPermissions returns permissions that a caller has on a Queue.
573// If the resource does not exist, this will return an empty set of
574// permissions, not a NOT_FOUND error.
575//
576// Note: This operation is designed to be used for building permission-aware
577// UIs and command-line tools, not for authorization checking. This operation
578// may “fail open” without warning.
579func (c *Client) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) {
580	if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines {
581		cctx, cancel := context.WithTimeout(ctx, 10000*time.Millisecond)
582		defer cancel()
583		ctx = cctx
584	}
585	md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource())))
586	ctx = insertMetadata(ctx, c.xGoogMetadata, md)
587	opts = append(c.CallOptions.TestIamPermissions[0:len(c.CallOptions.TestIamPermissions):len(c.CallOptions.TestIamPermissions)], opts...)
588	var resp *iampb.TestIamPermissionsResponse
589	err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
590		var err error
591		resp, err = c.client.TestIamPermissions(ctx, req, settings.GRPC...)
592		return err
593	}, opts...)
594	if err != nil {
595		return nil, err
596	}
597	return resp, nil
598}
599
600// ListTasks lists the tasks in a queue.
601//
602// By default, only the BASIC view is retrieved
603// due to performance considerations;
604// response_view controls the
605// subset of information which is returned.
606//
607// The tasks may be returned in any order. The ordering may change at any
608// time.
609func (c *Client) ListTasks(ctx context.Context, req *taskspb.ListTasksRequest, opts ...gax.CallOption) *TaskIterator {
610	md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent())))
611	ctx = insertMetadata(ctx, c.xGoogMetadata, md)
612	opts = append(c.CallOptions.ListTasks[0:len(c.CallOptions.ListTasks):len(c.CallOptions.ListTasks)], opts...)
613	it := &TaskIterator{}
614	req = proto.Clone(req).(*taskspb.ListTasksRequest)
615	it.InternalFetch = func(pageSize int, pageToken string) ([]*taskspb.Task, string, error) {
616		var resp *taskspb.ListTasksResponse
617		req.PageToken = pageToken
618		if pageSize > math.MaxInt32 {
619			req.PageSize = math.MaxInt32
620		} else {
621			req.PageSize = int32(pageSize)
622		}
623		err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
624			var err error
625			resp, err = c.client.ListTasks(ctx, req, settings.GRPC...)
626			return err
627		}, opts...)
628		if err != nil {
629			return nil, "", err
630		}
631
632		it.Response = resp
633		return resp.GetTasks(), resp.GetNextPageToken(), nil
634	}
635	fetch := func(pageSize int, pageToken string) (string, error) {
636		items, nextPageToken, err := it.InternalFetch(pageSize, pageToken)
637		if err != nil {
638			return "", err
639		}
640		it.items = append(it.items, items...)
641		return nextPageToken, nil
642	}
643	it.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf)
644	it.pageInfo.MaxSize = int(req.GetPageSize())
645	it.pageInfo.Token = req.GetPageToken()
646	return it
647}
648
649// GetTask gets a task.
650func (c *Client) GetTask(ctx context.Context, req *taskspb.GetTaskRequest, opts ...gax.CallOption) (*taskspb.Task, error) {
651	if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines {
652		cctx, cancel := context.WithTimeout(ctx, 10000*time.Millisecond)
653		defer cancel()
654		ctx = cctx
655	}
656	md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName())))
657	ctx = insertMetadata(ctx, c.xGoogMetadata, md)
658	opts = append(c.CallOptions.GetTask[0:len(c.CallOptions.GetTask):len(c.CallOptions.GetTask)], opts...)
659	var resp *taskspb.Task
660	err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
661		var err error
662		resp, err = c.client.GetTask(ctx, req, settings.GRPC...)
663		return err
664	}, opts...)
665	if err != nil {
666		return nil, err
667	}
668	return resp, nil
669}
670
671// CreateTask creates a task and adds it to a queue.
672//
673// Tasks cannot be updated after creation; there is no UpdateTask command.
674//
675//   The maximum task size is 100KB.
676func (c *Client) CreateTask(ctx context.Context, req *taskspb.CreateTaskRequest, opts ...gax.CallOption) (*taskspb.Task, error) {
677	if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines {
678		cctx, cancel := context.WithTimeout(ctx, 10000*time.Millisecond)
679		defer cancel()
680		ctx = cctx
681	}
682	md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent())))
683	ctx = insertMetadata(ctx, c.xGoogMetadata, md)
684	opts = append(c.CallOptions.CreateTask[0:len(c.CallOptions.CreateTask):len(c.CallOptions.CreateTask)], opts...)
685	var resp *taskspb.Task
686	err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
687		var err error
688		resp, err = c.client.CreateTask(ctx, req, settings.GRPC...)
689		return err
690	}, opts...)
691	if err != nil {
692		return nil, err
693	}
694	return resp, nil
695}
696
697// DeleteTask deletes a task.
698//
699// A task can be deleted if it is scheduled or dispatched. A task
700// cannot be deleted if it has executed successfully or permanently
701// failed.
702func (c *Client) DeleteTask(ctx context.Context, req *taskspb.DeleteTaskRequest, opts ...gax.CallOption) error {
703	if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines {
704		cctx, cancel := context.WithTimeout(ctx, 10000*time.Millisecond)
705		defer cancel()
706		ctx = cctx
707	}
708	md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName())))
709	ctx = insertMetadata(ctx, c.xGoogMetadata, md)
710	opts = append(c.CallOptions.DeleteTask[0:len(c.CallOptions.DeleteTask):len(c.CallOptions.DeleteTask)], opts...)
711	err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
712		var err error
713		_, err = c.client.DeleteTask(ctx, req, settings.GRPC...)
714		return err
715	}, opts...)
716	return err
717}
718
719// RunTask forces a task to run now.
720//
721// When this method is called, Cloud Tasks will dispatch the task, even if
722// the task is already running, the queue has reached its RateLimits or
723// is PAUSED.
724//
725// This command is meant to be used for manual debugging. For
726// example, RunTask can be used to retry a failed
727// task after a fix has been made or to manually force a task to be
728// dispatched now.
729//
730// The dispatched task is returned. That is, the task that is returned
731// contains the status after the task is dispatched but
732// before the task is received by its target.
733//
734// If Cloud Tasks receives a successful response from the task’s
735// target, then the task will be deleted; otherwise the task’s
736// schedule_time will be reset to the time that
737// RunTask was called plus the retry delay specified
738// in the queue’s RetryConfig.
739//
740// RunTask returns
741// NOT_FOUND when it is called on a
742// task that has already succeeded or permanently failed.
743func (c *Client) RunTask(ctx context.Context, req *taskspb.RunTaskRequest, opts ...gax.CallOption) (*taskspb.Task, error) {
744	if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines {
745		cctx, cancel := context.WithTimeout(ctx, 10000*time.Millisecond)
746		defer cancel()
747		ctx = cctx
748	}
749	md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName())))
750	ctx = insertMetadata(ctx, c.xGoogMetadata, md)
751	opts = append(c.CallOptions.RunTask[0:len(c.CallOptions.RunTask):len(c.CallOptions.RunTask)], opts...)
752	var resp *taskspb.Task
753	err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
754		var err error
755		resp, err = c.client.RunTask(ctx, req, settings.GRPC...)
756		return err
757	}, opts...)
758	if err != nil {
759		return nil, err
760	}
761	return resp, nil
762}
763
764// QueueIterator manages a stream of *taskspb.Queue.
765type QueueIterator struct {
766	items    []*taskspb.Queue
767	pageInfo *iterator.PageInfo
768	nextFunc func() error
769
770	// Response is the raw response for the current page.
771	// It must be cast to the RPC response type.
772	// Calling Next() or InternalFetch() updates this value.
773	Response interface{}
774
775	// InternalFetch is for use by the Google Cloud Libraries only.
776	// It is not part of the stable interface of this package.
777	//
778	// InternalFetch returns results from a single call to the underlying RPC.
779	// The number of results is no greater than pageSize.
780	// If there are no more results, nextPageToken is empty and err is nil.
781	InternalFetch func(pageSize int, pageToken string) (results []*taskspb.Queue, nextPageToken string, err error)
782}
783
784// PageInfo supports pagination. See the google.golang.org/api/iterator package for details.
785func (it *QueueIterator) PageInfo() *iterator.PageInfo {
786	return it.pageInfo
787}
788
789// Next returns the next result. Its second return value is iterator.Done if there are no more
790// results. Once Next returns Done, all subsequent calls will return Done.
791func (it *QueueIterator) Next() (*taskspb.Queue, error) {
792	var item *taskspb.Queue
793	if err := it.nextFunc(); err != nil {
794		return item, err
795	}
796	item = it.items[0]
797	it.items = it.items[1:]
798	return item, nil
799}
800
801func (it *QueueIterator) bufLen() int {
802	return len(it.items)
803}
804
805func (it *QueueIterator) takeBuf() interface{} {
806	b := it.items
807	it.items = nil
808	return b
809}
810
811// TaskIterator manages a stream of *taskspb.Task.
812type TaskIterator struct {
813	items    []*taskspb.Task
814	pageInfo *iterator.PageInfo
815	nextFunc func() error
816
817	// Response is the raw response for the current page.
818	// It must be cast to the RPC response type.
819	// Calling Next() or InternalFetch() updates this value.
820	Response interface{}
821
822	// InternalFetch is for use by the Google Cloud Libraries only.
823	// It is not part of the stable interface of this package.
824	//
825	// InternalFetch returns results from a single call to the underlying RPC.
826	// The number of results is no greater than pageSize.
827	// If there are no more results, nextPageToken is empty and err is nil.
828	InternalFetch func(pageSize int, pageToken string) (results []*taskspb.Task, nextPageToken string, err error)
829}
830
831// PageInfo supports pagination. See the google.golang.org/api/iterator package for details.
832func (it *TaskIterator) PageInfo() *iterator.PageInfo {
833	return it.pageInfo
834}
835
836// Next returns the next result. Its second return value is iterator.Done if there are no more
837// results. Once Next returns Done, all subsequent calls will return Done.
838func (it *TaskIterator) Next() (*taskspb.Task, error) {
839	var item *taskspb.Task
840	if err := it.nextFunc(); err != nil {
841		return item, err
842	}
843	item = it.items[0]
844	it.items = it.items[1:]
845	return item, nil
846}
847
848func (it *TaskIterator) bufLen() int {
849	return len(it.items)
850}
851
852func (it *TaskIterator) takeBuf() interface{} {
853	b := it.items
854	it.items = nil
855	return b
856}
857