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