initial commit

Signed-off-by: Derek McQuay <derekmcquay@gmail.com>
This commit is contained in:
dm
2018-04-10 19:17:26 -07:00
commit 59af8fc84f
2025 changed files with 456739 additions and 0 deletions
+45
View File
@@ -0,0 +1,45 @@
// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// AUTO-GENERATED CODE. DO NOT EDIT.
// Package longrunning is an auto-generated package for the
// Google Long Running Operations API.
//
// NOTE: This package is in alpha. It is not stable, and is likely to change.
//
//
// Use the client at cloud.google.com/go/longrunning in preference to this.
package longrunning // import "cloud.google.com/go/longrunning/autogen"
import (
"golang.org/x/net/context"
"google.golang.org/grpc/metadata"
)
func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context {
out, _ := metadata.FromOutgoingContext(ctx)
out = out.Copy()
for _, md := range mds {
for k, v := range md {
out[k] = append(out[k], v...)
}
}
return metadata.NewOutgoingContext(ctx, out)
}
// DefaultAuthScopes reports the default set of authentication scopes to use with this package.
func DefaultAuthScopes() []string {
return []string{}
}
+34
View File
@@ -0,0 +1,34 @@
// Copyright 2017, Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package longrunning
import (
longrunningpb "google.golang.org/genproto/googleapis/longrunning"
"google.golang.org/grpc"
)
// InternalFromConn is for use by the google Cloud Libraries only.
//
// InternalFromConn creates OperationsClient from available connection.
func InternalFromConn(conn *grpc.ClientConn) *OperationsClient {
c := &OperationsClient{
conn: conn,
CallOptions: defaultOperationsCallOptions(),
operationsClient: longrunningpb.NewOperationsClient(conn),
}
c.SetGoogleClientInfo()
return c
}
+381
View File
@@ -0,0 +1,381 @@
// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// AUTO-GENERATED CODE. DO NOT EDIT.
package longrunning
import (
emptypb "github.com/golang/protobuf/ptypes/empty"
longrunningpb "google.golang.org/genproto/googleapis/longrunning"
)
import (
"flag"
"fmt"
"io"
"log"
"net"
"os"
"strings"
"testing"
"github.com/golang/protobuf/proto"
"github.com/golang/protobuf/ptypes"
"golang.org/x/net/context"
"google.golang.org/api/option"
status "google.golang.org/genproto/googleapis/rpc/status"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
gstatus "google.golang.org/grpc/status"
)
var _ = io.EOF
var _ = ptypes.MarshalAny
var _ status.Status
type mockOperationsServer struct {
// Embed for forward compatibility.
// Tests will keep working if more methods are added
// in the future.
longrunningpb.OperationsServer
reqs []proto.Message
// If set, all calls return this error.
err error
// responses to return if err == nil
resps []proto.Message
}
func (s *mockOperationsServer) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest) (*longrunningpb.ListOperationsResponse, error) {
md, _ := metadata.FromIncomingContext(ctx)
if xg := md["x-goog-api-client"]; len(xg) == 0 || !strings.Contains(xg[0], "gl-go/") {
return nil, fmt.Errorf("x-goog-api-client = %v, expected gl-go key", xg)
}
s.reqs = append(s.reqs, req)
if s.err != nil {
return nil, s.err
}
return s.resps[0].(*longrunningpb.ListOperationsResponse), nil
}
func (s *mockOperationsServer) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest) (*longrunningpb.Operation, error) {
md, _ := metadata.FromIncomingContext(ctx)
if xg := md["x-goog-api-client"]; len(xg) == 0 || !strings.Contains(xg[0], "gl-go/") {
return nil, fmt.Errorf("x-goog-api-client = %v, expected gl-go key", xg)
}
s.reqs = append(s.reqs, req)
if s.err != nil {
return nil, s.err
}
return s.resps[0].(*longrunningpb.Operation), nil
}
func (s *mockOperationsServer) DeleteOperation(ctx context.Context, req *longrunningpb.DeleteOperationRequest) (*emptypb.Empty, error) {
md, _ := metadata.FromIncomingContext(ctx)
if xg := md["x-goog-api-client"]; len(xg) == 0 || !strings.Contains(xg[0], "gl-go/") {
return nil, fmt.Errorf("x-goog-api-client = %v, expected gl-go key", xg)
}
s.reqs = append(s.reqs, req)
if s.err != nil {
return nil, s.err
}
return s.resps[0].(*emptypb.Empty), nil
}
func (s *mockOperationsServer) CancelOperation(ctx context.Context, req *longrunningpb.CancelOperationRequest) (*emptypb.Empty, error) {
md, _ := metadata.FromIncomingContext(ctx)
if xg := md["x-goog-api-client"]; len(xg) == 0 || !strings.Contains(xg[0], "gl-go/") {
return nil, fmt.Errorf("x-goog-api-client = %v, expected gl-go key", xg)
}
s.reqs = append(s.reqs, req)
if s.err != nil {
return nil, s.err
}
return s.resps[0].(*emptypb.Empty), nil
}
// clientOpt is the option tests should use to connect to the test server.
// It is initialized by TestMain.
var clientOpt option.ClientOption
var (
mockOperations mockOperationsServer
)
func TestMain(m *testing.M) {
flag.Parse()
serv := grpc.NewServer()
longrunningpb.RegisterOperationsServer(serv, &mockOperations)
lis, err := net.Listen("tcp", "localhost:0")
if err != nil {
log.Fatal(err)
}
go serv.Serve(lis)
conn, err := grpc.Dial(lis.Addr().String(), grpc.WithInsecure())
if err != nil {
log.Fatal(err)
}
clientOpt = option.WithGRPCConn(conn)
os.Exit(m.Run())
}
func TestOperationsGetOperation(t *testing.T) {
var name2 string = "name2-1052831874"
var done bool = true
var expectedResponse = &longrunningpb.Operation{
Name: name2,
Done: done,
}
mockOperations.err = nil
mockOperations.reqs = nil
mockOperations.resps = append(mockOperations.resps[:0], expectedResponse)
var name string = "name3373707"
var request = &longrunningpb.GetOperationRequest{
Name: name,
}
c, err := NewOperationsClient(context.Background(), clientOpt)
if err != nil {
t.Fatal(err)
}
resp, err := c.GetOperation(context.Background(), request)
if err != nil {
t.Fatal(err)
}
if want, got := request, mockOperations.reqs[0]; !proto.Equal(want, got) {
t.Errorf("wrong request %q, want %q", got, want)
}
if want, got := expectedResponse, resp; !proto.Equal(want, got) {
t.Errorf("wrong response %q, want %q)", got, want)
}
}
func TestOperationsGetOperationError(t *testing.T) {
errCode := codes.PermissionDenied
mockOperations.err = gstatus.Error(errCode, "test error")
var name string = "name3373707"
var request = &longrunningpb.GetOperationRequest{
Name: name,
}
c, err := NewOperationsClient(context.Background(), clientOpt)
if err != nil {
t.Fatal(err)
}
resp, err := c.GetOperation(context.Background(), request)
if st, ok := gstatus.FromError(err); !ok {
t.Errorf("got error %v, expected grpc error", err)
} else if c := st.Code(); c != errCode {
t.Errorf("got error code %q, want %q", c, errCode)
}
_ = resp
}
func TestOperationsListOperations(t *testing.T) {
var nextPageToken string = ""
var operationsElement *longrunningpb.Operation = &longrunningpb.Operation{}
var operations = []*longrunningpb.Operation{operationsElement}
var expectedResponse = &longrunningpb.ListOperationsResponse{
NextPageToken: nextPageToken,
Operations: operations,
}
mockOperations.err = nil
mockOperations.reqs = nil
mockOperations.resps = append(mockOperations.resps[:0], expectedResponse)
var name string = "name3373707"
var filter string = "filter-1274492040"
var request = &longrunningpb.ListOperationsRequest{
Name: name,
Filter: filter,
}
c, err := NewOperationsClient(context.Background(), clientOpt)
if err != nil {
t.Fatal(err)
}
resp, err := c.ListOperations(context.Background(), request).Next()
if err != nil {
t.Fatal(err)
}
if want, got := request, mockOperations.reqs[0]; !proto.Equal(want, got) {
t.Errorf("wrong request %q, want %q", got, want)
}
want := (interface{})(expectedResponse.Operations[0])
got := (interface{})(resp)
var ok bool
switch want := (want).(type) {
case proto.Message:
ok = proto.Equal(want, got.(proto.Message))
default:
ok = want == got
}
if !ok {
t.Errorf("wrong response %q, want %q)", got, want)
}
}
func TestOperationsListOperationsError(t *testing.T) {
errCode := codes.PermissionDenied
mockOperations.err = gstatus.Error(errCode, "test error")
var name string = "name3373707"
var filter string = "filter-1274492040"
var request = &longrunningpb.ListOperationsRequest{
Name: name,
Filter: filter,
}
c, err := NewOperationsClient(context.Background(), clientOpt)
if err != nil {
t.Fatal(err)
}
resp, err := c.ListOperations(context.Background(), request).Next()
if st, ok := gstatus.FromError(err); !ok {
t.Errorf("got error %v, expected grpc error", err)
} else if c := st.Code(); c != errCode {
t.Errorf("got error code %q, want %q", c, errCode)
}
_ = resp
}
func TestOperationsCancelOperation(t *testing.T) {
var expectedResponse *emptypb.Empty = &emptypb.Empty{}
mockOperations.err = nil
mockOperations.reqs = nil
mockOperations.resps = append(mockOperations.resps[:0], expectedResponse)
var name string = "name3373707"
var request = &longrunningpb.CancelOperationRequest{
Name: name,
}
c, err := NewOperationsClient(context.Background(), clientOpt)
if err != nil {
t.Fatal(err)
}
err = c.CancelOperation(context.Background(), request)
if err != nil {
t.Fatal(err)
}
if want, got := request, mockOperations.reqs[0]; !proto.Equal(want, got) {
t.Errorf("wrong request %q, want %q", got, want)
}
}
func TestOperationsCancelOperationError(t *testing.T) {
errCode := codes.PermissionDenied
mockOperations.err = gstatus.Error(errCode, "test error")
var name string = "name3373707"
var request = &longrunningpb.CancelOperationRequest{
Name: name,
}
c, err := NewOperationsClient(context.Background(), clientOpt)
if err != nil {
t.Fatal(err)
}
err = c.CancelOperation(context.Background(), request)
if st, ok := gstatus.FromError(err); !ok {
t.Errorf("got error %v, expected grpc error", err)
} else if c := st.Code(); c != errCode {
t.Errorf("got error code %q, want %q", c, errCode)
}
}
func TestOperationsDeleteOperation(t *testing.T) {
var expectedResponse *emptypb.Empty = &emptypb.Empty{}
mockOperations.err = nil
mockOperations.reqs = nil
mockOperations.resps = append(mockOperations.resps[:0], expectedResponse)
var name string = "name3373707"
var request = &longrunningpb.DeleteOperationRequest{
Name: name,
}
c, err := NewOperationsClient(context.Background(), clientOpt)
if err != nil {
t.Fatal(err)
}
err = c.DeleteOperation(context.Background(), request)
if err != nil {
t.Fatal(err)
}
if want, got := request, mockOperations.reqs[0]; !proto.Equal(want, got) {
t.Errorf("wrong request %q, want %q", got, want)
}
}
func TestOperationsDeleteOperationError(t *testing.T) {
errCode := codes.PermissionDenied
mockOperations.err = gstatus.Error(errCode, "test error")
var name string = "name3373707"
var request = &longrunningpb.DeleteOperationRequest{
Name: name,
}
c, err := NewOperationsClient(context.Background(), clientOpt)
if err != nil {
t.Fatal(err)
}
err = c.DeleteOperation(context.Background(), request)
if st, ok := gstatus.FromError(err); !ok {
t.Errorf("got error %v, expected grpc error", err)
} else if c := st.Code(); c != errCode {
t.Errorf("got error code %q, want %q", c, errCode)
}
}
+267
View File
@@ -0,0 +1,267 @@
// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// AUTO-GENERATED CODE. DO NOT EDIT.
package longrunning
import (
"math"
"time"
"cloud.google.com/go/internal/version"
gax "github.com/googleapis/gax-go"
"golang.org/x/net/context"
"google.golang.org/api/iterator"
"google.golang.org/api/option"
"google.golang.org/api/transport"
longrunningpb "google.golang.org/genproto/googleapis/longrunning"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
)
// OperationsCallOptions contains the retry settings for each method of OperationsClient.
type OperationsCallOptions struct {
GetOperation []gax.CallOption
ListOperations []gax.CallOption
CancelOperation []gax.CallOption
DeleteOperation []gax.CallOption
}
func defaultOperationsClientOptions() []option.ClientOption {
return []option.ClientOption{
option.WithEndpoint("longrunning.googleapis.com:443"),
option.WithScopes(DefaultAuthScopes()...),
}
}
func defaultOperationsCallOptions() *OperationsCallOptions {
retry := map[[2]string][]gax.CallOption{
{"default", "idempotent"}: {
gax.WithRetry(func() gax.Retryer {
return gax.OnCodes([]codes.Code{
codes.DeadlineExceeded,
codes.Unavailable,
}, gax.Backoff{
Initial: 100 * time.Millisecond,
Max: 60000 * time.Millisecond,
Multiplier: 1.3,
})
}),
},
}
return &OperationsCallOptions{
GetOperation: retry[[2]string{"default", "idempotent"}],
ListOperations: retry[[2]string{"default", "idempotent"}],
CancelOperation: retry[[2]string{"default", "idempotent"}],
DeleteOperation: retry[[2]string{"default", "idempotent"}],
}
}
// OperationsClient is a client for interacting with Google Long Running Operations API.
type OperationsClient struct {
// The connection to the service.
conn *grpc.ClientConn
// The gRPC API client.
operationsClient longrunningpb.OperationsClient
// The call options for this service.
CallOptions *OperationsCallOptions
// The x-goog-* metadata to be sent with each request.
xGoogMetadata metadata.MD
}
// NewOperationsClient creates a new operations client.
//
// Manages long-running operations with an API service.
//
// When an API method normally takes long time to complete, it can be designed
// to return [Operation][google.longrunning.Operation] to the client, and the client can use this
// interface to receive the real response asynchronously by polling the
// operation resource, or pass the operation resource to another API (such as
// Google Cloud Pub/Sub API) to receive the response. Any API service that
// returns long-running operations should implement the Operations interface
// so developers can have a consistent client experience.
func NewOperationsClient(ctx context.Context, opts ...option.ClientOption) (*OperationsClient, error) {
conn, err := transport.DialGRPC(ctx, append(defaultOperationsClientOptions(), opts...)...)
if err != nil {
return nil, err
}
c := &OperationsClient{
conn: conn,
CallOptions: defaultOperationsCallOptions(),
operationsClient: longrunningpb.NewOperationsClient(conn),
}
c.SetGoogleClientInfo()
return c, nil
}
// Connection returns the client's connection to the API service.
func (c *OperationsClient) Connection() *grpc.ClientConn {
return c.conn
}
// Close closes the connection to the API service. The user should invoke this when
// the client is no longer required.
func (c *OperationsClient) Close() error {
return c.conn.Close()
}
// SetGoogleClientInfo sets the name and version of the application in
// the `x-goog-api-client` header passed on each request. Intended for
// use by Google-written clients.
func (c *OperationsClient) SetGoogleClientInfo(keyval ...string) {
kv := append([]string{"gl-go", version.Go()}, keyval...)
kv = append(kv, "gapic", version.Repo, "gax", gax.Version, "grpc", grpc.Version)
c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...))
}
// GetOperation gets the latest state of a long-running operation. Clients can use this
// method to poll the operation result at intervals as recommended by the API
// service.
func (c *OperationsClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) {
ctx = insertMetadata(ctx, c.xGoogMetadata)
opts = append(c.CallOptions.GetOperation[0:len(c.CallOptions.GetOperation):len(c.CallOptions.GetOperation)], opts...)
var resp *longrunningpb.Operation
err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
var err error
resp, err = c.operationsClient.GetOperation(ctx, req, settings.GRPC...)
return err
}, opts...)
if err != nil {
return nil, err
}
return resp, nil
}
// ListOperations lists operations that match the specified filter in the request. If the
// server doesn't support this method, it returns UNIMPLEMENTED.
//
// NOTE: the name binding below allows API services to override the binding
// to use different resource name schemes, such as users/*/operations.
func (c *OperationsClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator {
ctx = insertMetadata(ctx, c.xGoogMetadata)
opts = append(c.CallOptions.ListOperations[0:len(c.CallOptions.ListOperations):len(c.CallOptions.ListOperations)], opts...)
it := &OperationIterator{}
it.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) {
var resp *longrunningpb.ListOperationsResponse
req.PageToken = pageToken
if pageSize > math.MaxInt32 {
req.PageSize = math.MaxInt32
} else {
req.PageSize = int32(pageSize)
}
err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
var err error
resp, err = c.operationsClient.ListOperations(ctx, req, settings.GRPC...)
return err
}, opts...)
if err != nil {
return nil, "", err
}
return resp.Operations, resp.NextPageToken, nil
}
fetch := func(pageSize int, pageToken string) (string, error) {
items, nextPageToken, err := it.InternalFetch(pageSize, pageToken)
if err != nil {
return "", err
}
it.items = append(it.items, items...)
return nextPageToken, nil
}
it.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf)
return it
}
// CancelOperation starts asynchronous cancellation on a long-running operation. The server
// makes a best effort to cancel the operation, but success is not
// guaranteed. If the server doesn't support this method, it returns
// google.rpc.Code.UNIMPLEMENTED. Clients can use
// [Operations.GetOperation][google.longrunning.Operations.GetOperation] or
// other methods to check whether the cancellation succeeded or whether the
// operation completed despite cancellation. On successful cancellation,
// the operation is not deleted; instead, it becomes an operation with
// an [Operation.error][google.longrunning.Operation.error] value with a [google.rpc.Status.code][google.rpc.Status.code] of 1,
// corresponding to Code.CANCELLED.
func (c *OperationsClient) CancelOperation(ctx context.Context, req *longrunningpb.CancelOperationRequest, opts ...gax.CallOption) error {
ctx = insertMetadata(ctx, c.xGoogMetadata)
opts = append(c.CallOptions.CancelOperation[0:len(c.CallOptions.CancelOperation):len(c.CallOptions.CancelOperation)], opts...)
err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
var err error
_, err = c.operationsClient.CancelOperation(ctx, req, settings.GRPC...)
return err
}, opts...)
return err
}
// DeleteOperation deletes a long-running operation. This method indicates that the client is
// no longer interested in the operation result. It does not cancel the
// operation. If the server doesn't support this method, it returns
// google.rpc.Code.UNIMPLEMENTED.
func (c *OperationsClient) DeleteOperation(ctx context.Context, req *longrunningpb.DeleteOperationRequest, opts ...gax.CallOption) error {
ctx = insertMetadata(ctx, c.xGoogMetadata)
opts = append(c.CallOptions.DeleteOperation[0:len(c.CallOptions.DeleteOperation):len(c.CallOptions.DeleteOperation)], opts...)
err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
var err error
_, err = c.operationsClient.DeleteOperation(ctx, req, settings.GRPC...)
return err
}, opts...)
return err
}
// OperationIterator manages a stream of *longrunningpb.Operation.
type OperationIterator struct {
items []*longrunningpb.Operation
pageInfo *iterator.PageInfo
nextFunc func() error
// InternalFetch is for use by the Google Cloud Libraries only.
// It is not part of the stable interface of this package.
//
// InternalFetch returns results from a single call to the underlying RPC.
// The number of results is no greater than pageSize.
// If there are no more results, nextPageToken is empty and err is nil.
InternalFetch func(pageSize int, pageToken string) (results []*longrunningpb.Operation, nextPageToken string, err error)
}
// PageInfo supports pagination. See the google.golang.org/api/iterator package for details.
func (it *OperationIterator) PageInfo() *iterator.PageInfo {
return it.pageInfo
}
// Next returns the next result. Its second return value is iterator.Done if there are no more
// results. Once Next returns Done, all subsequent calls will return Done.
func (it *OperationIterator) Next() (*longrunningpb.Operation, error) {
var item *longrunningpb.Operation
if err := it.nextFunc(); err != nil {
return item, err
}
item = it.items[0]
it.items = it.items[1:]
return item, nil
}
func (it *OperationIterator) bufLen() int {
return len(it.items)
}
func (it *OperationIterator) takeBuf() interface{} {
b := it.items
it.items = nil
return b
}
@@ -0,0 +1,108 @@
// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// AUTO-GENERATED CODE. DO NOT EDIT.
package longrunning_test
import (
"cloud.google.com/go/longrunning/autogen"
"golang.org/x/net/context"
"google.golang.org/api/iterator"
longrunningpb "google.golang.org/genproto/googleapis/longrunning"
)
func ExampleNewOperationsClient() {
ctx := context.Background()
c, err := longrunning.NewOperationsClient(ctx)
if err != nil {
// TODO: Handle error.
}
// TODO: Use client.
_ = c
}
func ExampleOperationsClient_GetOperation() {
ctx := context.Background()
c, err := longrunning.NewOperationsClient(ctx)
if err != nil {
// TODO: Handle error.
}
req := &longrunningpb.GetOperationRequest{
// TODO: Fill request struct fields.
}
resp, err := c.GetOperation(ctx, req)
if err != nil {
// TODO: Handle error.
}
// TODO: Use resp.
_ = resp
}
func ExampleOperationsClient_ListOperations() {
ctx := context.Background()
c, err := longrunning.NewOperationsClient(ctx)
if err != nil {
// TODO: Handle error.
}
req := &longrunningpb.ListOperationsRequest{
// TODO: Fill request struct fields.
}
it := c.ListOperations(ctx, req)
for {
resp, err := it.Next()
if err == iterator.Done {
break
}
if err != nil {
// TODO: Handle error.
}
// TODO: Use resp.
_ = resp
}
}
func ExampleOperationsClient_CancelOperation() {
ctx := context.Background()
c, err := longrunning.NewOperationsClient(ctx)
if err != nil {
// TODO: Handle error.
}
req := &longrunningpb.CancelOperationRequest{
// TODO: Fill request struct fields.
}
err = c.CancelOperation(ctx, req)
if err != nil {
// TODO: Handle error.
}
}
func ExampleOperationsClient_DeleteOperation() {
ctx := context.Background()
c, err := longrunning.NewOperationsClient(ctx)
if err != nil {
// TODO: Handle error.
}
req := &longrunningpb.DeleteOperationRequest{
// TODO: Fill request struct fields.
}
err = c.DeleteOperation(ctx, req)
if err != nil {
// TODO: Handle error.
}
}
+116
View File
@@ -0,0 +1,116 @@
// Copyright 2016 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package longrunning
import (
"fmt"
"time"
"github.com/golang/protobuf/ptypes"
"github.com/golang/protobuf/ptypes/duration"
"github.com/golang/protobuf/ptypes/timestamp"
"golang.org/x/net/context"
pb "google.golang.org/genproto/googleapis/longrunning"
)
func bestMomentInHistory() (*Operation, error) {
t, err := time.Parse("2006-01-02 15:04:05.999999999 -0700 MST", "2009-11-10 23:00:00 +0000 UTC")
if err != nil {
return nil, err
}
resp, err := ptypes.TimestampProto(t)
if err != nil {
return nil, err
}
respAny, err := ptypes.MarshalAny(resp)
if err != nil {
return nil, err
}
metaAny, err := ptypes.MarshalAny(ptypes.DurationProto(1 * time.Hour))
return &Operation{
proto: &pb.Operation{
Name: "best-moment",
Done: true,
Metadata: metaAny,
Result: &pb.Operation_Response{
Response: respAny,
},
},
}, err
}
func ExampleOperation_Wait() {
// Complex computation, might take a long time.
op, err := bestMomentInHistory()
if err != nil {
// TODO: Handle err.
}
var ts timestamp.Timestamp
err = op.Wait(context.TODO(), &ts)
if err != nil && !op.Done() {
fmt.Println("failed to fetch operation status", err)
} else if err != nil && op.Done() {
fmt.Println("operation completed with error", err)
} else {
fmt.Println(ptypes.TimestampString(&ts))
}
// Output:
// 2009-11-10T23:00:00Z
}
func ExampleOperation_Metadata() {
op, err := bestMomentInHistory()
if err != nil {
// TODO: Handle err.
}
// The operation might contain metadata.
// In this example, the metadata contains the estimated length of time
// the operation might take to complete.
var meta duration.Duration
if err := op.Metadata(&meta); err != nil {
// TODO: Handle err.
}
d, err := ptypes.Duration(&meta)
if err == ErrNoMetadata {
fmt.Println("no metadata")
} else if err != nil {
// TODO: Handle err.
} else {
fmt.Println(d)
}
// Output:
// 1h0m0s
}
func ExampleOperation_Cancel() {
op, err := bestMomentInHistory()
if err != nil {
// TODO: Handle err.
}
if err := op.Cancel(context.Background()); err != nil {
// TODO: Handle err.
}
}
func ExampleOperation_Delete() {
op, err := bestMomentInHistory()
if err != nil {
// TODO: Handle err.
}
if err := op.Delete(context.Background()); err != nil {
// TODO: Handle err.
}
}
+181
View File
@@ -0,0 +1,181 @@
// Copyright 2016 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Package longrunning supports Long Running Operations for the Google Cloud Libraries.
// See google.golang.org/genproto/googleapis/longrunning for its service definition.
//
// Users of the Google Cloud Libraries will typically not use this package directly.
// Instead they will call functions returning Operations and call their methods.
//
// This package is still experimental and subject to change.
package longrunning // import "cloud.google.com/go/longrunning"
import (
"errors"
"fmt"
"time"
"github.com/golang/protobuf/proto"
"github.com/golang/protobuf/ptypes"
"github.com/googleapis/gax-go"
"google.golang.org/grpc/status"
"golang.org/x/net/context"
autogen "cloud.google.com/go/longrunning/autogen"
pb "google.golang.org/genproto/googleapis/longrunning"
"google.golang.org/grpc/codes"
)
// ErrNoMetadata is the error returned by Metadata if the operation contains no metadata.
var ErrNoMetadata = errors.New("operation contains no metadata")
// Operation represents the result of an API call that may not be ready yet.
type Operation struct {
c operationsClient
proto *pb.Operation
}
type operationsClient interface {
GetOperation(context.Context, *pb.GetOperationRequest, ...gax.CallOption) (*pb.Operation, error)
CancelOperation(context.Context, *pb.CancelOperationRequest, ...gax.CallOption) error
DeleteOperation(context.Context, *pb.DeleteOperationRequest, ...gax.CallOption) error
}
// InternalNewOperation is for use by the google Cloud Libraries only.
//
// InternalNewOperation returns an long-running operation, abstracting the raw pb.Operation.
// The conn parameter refers to a server that proto was received from.
func InternalNewOperation(inner *autogen.OperationsClient, proto *pb.Operation) *Operation {
return &Operation{
c: inner,
proto: proto,
}
}
// Name returns the name of the long-running operation.
// The name is assigned by the server and is unique within the service
// from which the operation is created.
func (op *Operation) Name() string {
return op.proto.Name
}
// Done reports whether the long-running operation has completed.
func (op *Operation) Done() bool {
return op.proto.Done
}
// Metadata unmarshals op's metadata into meta.
// If op does not contain any metadata, Metadata returns ErrNoMetadata and meta is unmodified.
func (op *Operation) Metadata(meta proto.Message) error {
if m := op.proto.Metadata; m != nil {
return ptypes.UnmarshalAny(m, meta)
}
return ErrNoMetadata
}
// Poll fetches the latest state of a long-running operation.
//
// If Poll fails, the error is returned and op is unmodified.
// If Poll succeeds and the operation has completed with failure,
// the error is returned and op.Done will return true.
// If Poll succeeds and the operation has completed successfully,
// op.Done will return true; if resp != nil, the response of the operation
// is stored in resp.
func (op *Operation) Poll(ctx context.Context, resp proto.Message, opts ...gax.CallOption) error {
if !op.Done() {
p, err := op.c.GetOperation(ctx, &pb.GetOperationRequest{Name: op.Name()}, opts...)
if err != nil {
return err
}
op.proto = p
}
if !op.Done() {
return nil
}
switch r := op.proto.Result.(type) {
case *pb.Operation_Error:
// TODO (pongad): r.Details may contain further information
return status.Errorf(codes.Code(r.Error.Code), "%s", r.Error.Message)
case *pb.Operation_Response:
if resp == nil {
return nil
}
return ptypes.UnmarshalAny(r.Response, resp)
default:
return fmt.Errorf("unsupported result type %[1]T: %[1]v", r)
}
}
// DefaultWaitInterval is the polling interval used by Operation.Wait.
const DefaultWaitInterval = 60 * time.Second
// Wait is equivalent to WaitWithInterval using DefaultWaitInterval.
func (op *Operation) Wait(ctx context.Context, resp proto.Message, opts ...gax.CallOption) error {
return op.WaitWithInterval(ctx, resp, DefaultWaitInterval, opts...)
}
// WaitWithInterval blocks until the operation is completed.
// If resp != nil, Wait stores the response in resp.
// WaitWithInterval polls every interval, except initially
// when it polls using exponential backoff.
//
// See documentation of Poll for error-handling information.
func (op *Operation) WaitWithInterval(ctx context.Context, resp proto.Message, interval time.Duration, opts ...gax.CallOption) error {
bo := gax.Backoff{
Initial: 1 * time.Second,
Max: interval,
}
if bo.Max < bo.Initial {
bo.Max = bo.Initial
}
return op.wait(ctx, resp, &bo, gax.Sleep, opts...)
}
type sleeper func(context.Context, time.Duration) error
// wait implements Wait, taking exponentialBackoff and sleeper arguments for testing.
func (op *Operation) wait(ctx context.Context, resp proto.Message, bo *gax.Backoff, sl sleeper, opts ...gax.CallOption) error {
for {
if err := op.Poll(ctx, resp, opts...); err != nil {
return err
}
if op.Done() {
return nil
}
if err := sl(ctx, bo.Pause()); err != nil {
return err
}
}
}
// Cancel starts asynchronous cancellation on a long-running operation. The server
// makes a best effort to cancel the operation, but success is not
// guaranteed. If the server doesn't support this method, it returns
// grpc.Code(error) == codes.Unimplemented. Clients can use
// Poll or other methods to check whether the cancellation succeeded or whether the
// operation completed despite cancellation. On successful cancellation,
// the operation is not deleted; instead, op.Poll returns an error
// with code Canceled.
func (op *Operation) Cancel(ctx context.Context, opts ...gax.CallOption) error {
return op.c.CancelOperation(ctx, &pb.CancelOperationRequest{Name: op.Name()}, opts...)
}
// Delete deletes a long-running operation. This method indicates that the client is
// no longer interested in the operation result. It does not cancel the
// operation. If the server doesn't support this method, grpc.Code(error) == codes.Unimplemented.
func (op *Operation) Delete(ctx context.Context, opts ...gax.CallOption) error {
return op.c.DeleteOperation(ctx, &pb.DeleteOperationRequest{Name: op.Name()}, opts...)
}
+215
View File
@@ -0,0 +1,215 @@
// Copyright 2016 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Package lro supports Long Running Operations for the Google Cloud Libraries.
//
// This package is still experimental and subject to change.
package longrunning
import (
"errors"
"testing"
"time"
"github.com/golang/protobuf/proto"
"github.com/golang/protobuf/ptypes"
"github.com/golang/protobuf/ptypes/duration"
gax "github.com/googleapis/gax-go"
"golang.org/x/net/context"
pb "google.golang.org/genproto/googleapis/longrunning"
status "google.golang.org/genproto/googleapis/rpc/status"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
)
type getterService struct {
operationsClient
// clock represents the fake current time of the service.
// It is the running sum of the of the duration we have slept.
clock time.Duration
// getTimes records the the times at which GetOperation is called.
getTimes []time.Duration
// results are the fake results that GetOperation should return.
results []*pb.Operation
}
func (s *getterService) GetOperation(context.Context, *pb.GetOperationRequest, ...gax.CallOption) (*pb.Operation, error) {
i := len(s.getTimes)
s.getTimes = append(s.getTimes, s.clock)
if i >= len(s.results) {
return nil, errors.New("unexpected call")
}
return s.results[i], nil
}
func (s *getterService) sleeper() sleeper {
return func(_ context.Context, d time.Duration) error {
s.clock += d
return nil
}
}
func TestWait(t *testing.T) {
responseDur := ptypes.DurationProto(42 * time.Second)
responseAny, err := ptypes.MarshalAny(responseDur)
if err != nil {
t.Fatal(err)
}
s := &getterService{
results: []*pb.Operation{
{Name: "foo"},
{Name: "foo"},
{Name: "foo"},
{Name: "foo"},
{Name: "foo"},
{
Name: "foo",
Done: true,
Result: &pb.Operation_Response{
Response: responseAny,
},
},
},
}
op := &Operation{
c: s,
proto: &pb.Operation{Name: "foo"},
}
if op.Done() {
t.Fatal("operation should not have completed yet")
}
var resp duration.Duration
bo := gax.Backoff{
Initial: 1 * time.Second,
Max: 3 * time.Second,
}
if err := op.wait(context.Background(), &resp, &bo, s.sleeper()); err != nil {
t.Fatal(err)
}
if !proto.Equal(&resp, responseDur) {
t.Errorf("response, got %v, want %v", resp, responseDur)
}
if !op.Done() {
t.Errorf("operation should have completed")
}
maxWait := []time.Duration{
1 * time.Second,
2 * time.Second,
3 * time.Second,
3 * time.Second,
3 * time.Second,
}
for i := 0; i < len(s.getTimes)-1; i++ {
w := s.getTimes[i+1] - s.getTimes[i]
if mw := maxWait[i]; w > mw {
t.Errorf("backoff, waited %s, max %s", w, mw)
}
}
}
func TestPollRequestError(t *testing.T) {
const opName = "foo"
// All calls error.
s := &getterService{}
op := &Operation{
c: s,
proto: &pb.Operation{Name: opName},
}
if err := op.Poll(context.Background(), nil); err == nil {
t.Fatalf("Poll should error")
}
if n := op.Name(); n != opName {
t.Errorf("operation name, got %q, want %q", n, opName)
}
if op.Done() {
t.Errorf("operation should not have completed; we failed to fetch state")
}
}
func TestPollErrorResult(t *testing.T) {
const (
errCode = codes.NotFound
errMsg = "my error"
)
op := &Operation{
proto: &pb.Operation{
Name: "foo",
Done: true,
Result: &pb.Operation_Error{
Error: &status.Status{
Code: int32(errCode),
Message: errMsg,
},
},
},
}
err := op.Poll(context.Background(), nil)
if got := grpc.Code(err); got != errCode {
t.Errorf("error code, want %s, got %s", errCode, got)
}
if got := grpc.ErrorDesc(err); got != errMsg {
t.Errorf("error code, want %s, got %s", errMsg, got)
}
if !op.Done() {
t.Errorf("operation should have completed")
}
}
type errService struct {
operationsClient
errCancel, errDelete error
}
func (s *errService) CancelOperation(context.Context, *pb.CancelOperationRequest, ...gax.CallOption) error {
return s.errCancel
}
func (s *errService) DeleteOperation(context.Context, *pb.DeleteOperationRequest, ...gax.CallOption) error {
return s.errDelete
}
func TestCancelReturnsError(t *testing.T) {
s := &errService{
errCancel: errors.New("cancel error"),
}
op := &Operation{
c: s,
proto: &pb.Operation{Name: "foo"},
}
if got, want := op.Cancel(context.Background()), s.errCancel; got != want {
t.Errorf("cancel, got error %s, want %s", got, want)
}
}
func TestDeleteReturnsError(t *testing.T) {
s := &errService{
errDelete: errors.New("delete error"),
}
op := &Operation{
c: s,
proto: &pb.Operation{Name: "foo"},
}
if got, want := op.Delete(context.Background()), s.errDelete; got != want {
t.Errorf("cancel, got error %s, want %s", got, want)
}
}